为什么std :: function在这种情况下不起作用?

Ale*_*llo 4 c++ stl function most-vexing-parse c++11

想象一下我有一个类型:

struct my_type
{
    double operator()(int a)
    {
        return 3.1415;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后我想把它包起来std::function.考虑两种不同的方法:

my_type m_t;
std::function<double(int)> f(std::move(m_t));
std::cout << f(4) << std::endl;
Run Code Online (Sandbox Code Playgroud)

如我所料,一切都很好,打印出PI的第一个数字.然后是第二种方法:

std::function<double(int)> ff(my_type()); 
std::cout << ff(4) << std::endl;
Run Code Online (Sandbox Code Playgroud)

在我看来,这个代码是完全一样的第一个.rvalue作为function包装器的参数传递.但问题是,第二个代码不能编译!我真的不知道为什么会这样.

son*_*yao 10

这是着名的最令人烦恼的解析问题.因为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{}}; 
Run Code Online (Sandbox Code Playgroud)

生活