Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 549
Liang Tan Avatar asked Dec 02 '14 14:12

Liang Tan


1 Answers

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.

like image 177
Joseph Mansfield Avatar answered Oct 06 '22 17:10

Joseph Mansfield