Search code examples
c++c++11most-vexing-parse

Pass anonymous function object to std::function?


Here is my question: I define a functor:

class A { 
 public: 
   int operator()(int a, int b) const{
    return a + b;
   }
 };
typedef function<int (int, int)> Fun;

then I use a anonymous functor to create a std::function object, and I find something strange. Here is my code:

Fun f(A());
f(3, 4);

Unfortunately it is wrong. The error message is:

error: invalid conversion from ‘int’ to ‘A (*)()’ [-fpermissive]
error: too many arguments to function ‘Fun f(A (*)())’

However, when I change my code as follow:

A a;
Fun f(a);
f(3, 4);

or

Fun f = A();
f(3, 4);

The result is right. So, why is it? Help me understand it,please. Thanks.


Solution

  • Fun f(A());
    

    This is a case of the most-vexing parse. It declares a function f which returns a Fun. It takes a function pointer as an argument, pointing at a function that takes no arguments and returns an A.

    There are a few ways to get around this:

    Fun f{A()};    // Uniform-initialisation syntax
    Fun f{A{}};    // Uniform-initialisation on both objects
    Fun f((A()));  // Forcing the initialiser to be an expression, not parameter list
    

    Or one of the things you did.