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?
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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With