Pass anonymous function object to std::function?

岁酱吖の 提交于 2019-12-19 17:19:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/27252065/pass-anonymous-function-object-to-stdfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!