Search code examples
c++c++11gotw

C++'s most vexing parse again


Taken directly from http://herbsutter.com/2013/05/09/gotw-1-solution/

While widget w(); is clear for me, I have no idea how can the below code be a function declaration?

// same problem (gadget and doodad are types)
//
widget w( gadget(), doodad() );  // pitfall: not a variable declaration

How is this possible?


Solution

  • In a function declaration, arguments of type array decay into pointers to the first element, arguments of type function decay into a function pointer, so the signature would be:

    widget w( gadget(*)(), doodad(*)() );
    

    That is, a function that takes as the first argument a pointer to a function taking no arguments and returning gadget, that takes as second argument a pointer to a function taking no arguments and returning a doodad and that the function itself returns a widget

    There are even more interesting or confusing cases, like:

    // assume 'x' is a variable defined somewhere:
    widget w(gadget(x));
    

    How could that be interpreted as a function declaration? I mean, x is a variable, right? Well, when declaring a variable you can add extra parenthesis, so gadget x; and gadget (x); both declare the same variable x. The same applies to function arguments so the code above looks like a declaration of a function that takes a first argument named x of type gadget and returns a widget...