将匿名函数对象传递给std :: function? [英] 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;
那么我使用匿名函数创建一个std :: function对象,这是我的代码:
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);
或
Fun f = A();
f(3, 4);
结果是正确的。
那么,为什么呢?请帮助我理解它。感谢。
The result is right. So, why is it? Help me understand it,please. Thanks.
推荐答案
Fun f(A());
这是最讨厌的解析。它声明一个函数 f
,它返回一个 Fun
。它接受一个函数指针作为参数,指向一个不带参数的函数,并返回一个 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
这篇关于将匿名函数对象传递给std :: function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!