Prototyped function of structures

Today I came across this code:

int main() { struct Foo {}; struct Bar {}; Foo(b)(int (Bar*c)); // ? return 0; } 

I have no idea what is going on. Is my compiler (VC14) warning me of an unused prototype function?

What does this line do (declare a function: what name, what parameters and return type? What should I call it?)

 Foo(b)(int (Bar*c)); 

Thank you in advance for your help!

+7
c ++ function struct prototype
source share
3 answers

This declares a function called b , which:

  • takes int (Bar*c) as an argument;
  • returns Foo .

The argument type int (Bar*c) , is a pointer to a function that takes a pointer to Bar and returns int . Here c is the name of the argument and can be omitted: int (Bar*) .

Here's what you can call b :

 int main() { struct Foo {}; struct Bar {}; Foo(b)(int (Bar* c)); // the prototype in question int func(Bar*); // a function defined elsewhere Foo result = b(func); return 0; } 
+6
source share

This is not valid C (because the names Foo and Bar not type specific, you will need to use the struct keyword or use typedef).

In C ++, this is an amazing but valid declaration. It declares b as a function returning Foo, and takes an argument to a type function (pointer to), returning an int, taking the argument of a type pointer to Bar.

To create a declaration of a readable type, I wrote the following code:

 #include <typeinfo> #include <iostream> int main() { struct Foo {}; struct Bar {}; Foo(b)(int (Bar*c)); std::cout << typeid(b).name(); return 0; } 

Then I compiled it and filtered its output through c++filt . The result is:

 main::Foo (int (*)(main::Bar*)) 

which is completely clear.

+4
source share

Actually, my compiler (Clang 3.5) gives me the following warning:

warning: parentheses were ambiguous as a function declaration [-Wvexing parsing]

More importantly, since you are dealing with the most unpleasant parsing .

Next announcement:

 Foo(b)(int (Bar*c)); 

declares a function pointer b that points to a function that returns Foo , and takes as an argument a function that returns int , and takes a pointer to a Bar argument (for example,: int (Bar*c) ).

Perhaps your compiler thinks this is a function prototype, so a warning.

+2
source share

All Articles