假设我有一个类型:
struct my_type
{
double operator()(int a)
{
return 3.1415;
}
};
然后我想将它包装在 std::function
中。考虑两种不同的方法:
my_type m_t;
std::function<double(int)> f(std::move(m_t));
std::cout << f(4) << std::endl;
一切如我所料,打印出了 PI 的第一位数字。然后第二种方法:
std::function<double(int)> ff(my_type());
std::cout << ff(4) << std::endl;
在我看来,这段代码与第一个代码绝对相同。 rvalue
作为参数传递给 function
包装器。但问题是,第二个代码无法编译!我真的不知道为什么会这样。
最佳答案
这就是著名的most vexing parse问题。对于 std::function<double(int)> ff(my_type());
,您没有声明 std::function<double(int)>
类型的对象如您所料,但是一个名为 ff
的函数, 它返回类型为 std::function<double(int)>
的对象并且有一个(未命名的)参数,它是指向函数返回类型 my_type
的指针并且不接受任何输入。
要解决此问题,您可以添加额外的括号或使用 C++11 支持的大括号(大括号可用于消除歧义,因为它不能用于参数列表)。例如
std::function<double(int)> ff1((my_type()));
std::function<double(int)> ff2(my_type{});
std::function<double(int)> ff3{my_type()};
std::function<double(int)> ff4{my_type{}};
关于c++ - 为什么 std::function 在这种情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41357285/