Why can't variables defined in a conditional be constructed with arguments?

前端 未结 5 2089
星月不相逢
星月不相逢 2020-12-16 11:05

The question is simple. Why does this compile:

bool b(true);
if (b) { /* */ }

And this compile:

if (bool b = true) { /* */         


        
5条回答
  •  眼角桃花
    2020-12-16 11:36

    It should be noted.that if(functor(f)(123)) ...; would then not be the call of an anonymous functor with argument 123 anymore but would declare a functor initialized by 123.

    And i think introducing such pitfalls for that little feature is not worth it.


    Since it may not be clear what the above means, let's take a deeper look. First remember that parentheses around a declarator are allowed, including for the degenerate case of being directly around a declared name:

    int(n) = 0; 
    // same: int n = 0; 
    
    int(n)(0);
    // same: int n(0);
    

    Both of the parenthesized versions are ambiguous, because the first could be an assignment and the second could be a function call. But both could also be declarations. And the Standard says that they are declarations.

    If we will allow paren-initializers in conditions, then we introduce the latter ambiguity into conditions too, just as for the statement case. Thus we would make valid condition expressions that are used nowadays into declarations after the feature is supported. Consider

    typedef bool(*handler_type)(int);
    
    bool f(int) { /* ... */ }
    bool f(int, int) { /* ... */ }
    
    void call_it() {
       // user wants to call f(int), but it is overloaded!
       // -> user tries a cast...
       if(handler_type(f)(0)) {
         /* ... */
       }
    }
    

    What you think will happen? Of course, it will never enter the if body, because it always declares a null pointer. It never calls function f. Without the "feature" it will properly call f, because we don't have the ambiguity. This is not limited to only (f), but also (*f) (declares a pointer), (&f) (declares a reference) et al.

    Again: Do we want such pitfalls as price for such a small feature? I don't know how many people even know they could declare stuff in a condition.

提交回复
热议问题