为什么在这种情况下std :: function不起作用?
问题描述:
想象我有一个类型:为什么在这种情况下std :: function不起作用?
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());
,你不declaraing 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{}};