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

Why doesn't std::function work in this situation?

假设我有一个类型:

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 的函数,其中 returns 是一个类型为 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{}}; 

LIVE