C++'s most vexing parse again [duplicate]

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 1:

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...

Solution 2:

It's function that gets two functions, that returns gadget and doodad and either of them gets no arguments.

Example that compiles fine.

#include <iostream>
class widget{};
class gadget{};
class doodad{};
gadget a(){}
doodad b() {};
widget w( gadget(), doodad() ){
}
int main() {
    w(a,b);
    return 0;
}

http://ideone.com/YjZK9Y