将 Functor 转换为 Object of Type 函数

Converting a Functor to an Object of Type function

假设我有这个功能:

template <typename T>
void foo(function<T(const T&, const T&)> op, const T& lhs, const T& rhs) {
    cout << op(lhs, rhs) << endl;
}

这是legal code:

function<int(const int&, const int&)> op = plus<int>();

foo(op, 13, 42);

但是当我这样做时:

foo(plus<int>(), 13, 42)

我收到错误:

No matching function for call to foo(std::plus<int>, int, int)

为什么我可以从 plus<int>() 初始化 function<int(const int&, const int&)> 类型的对象,但我不能将 plus<int>() 传递给 function<T(const T&, const T&)> 类型的参数?跟模板有关系吗?

引自标准第 14.8.1.6 节:

Implicit conversions (Clause 4) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument deduction.

这不适用于您的情况,因为尚未明确提供模板参数。编译器需要进行推导。因此,按照上述,它不会进行从仿函数到 std::function.

的隐式转换

所以,你可以这样做(正如@flatmouse 在评论中提到的):

foo<int>(plus<int>(), 13, 42);

这是可行的,因为所有模板参数都已明确指定,因此无需执行模板参数推导。根据上面引用的标准,隐式转换应该适用于此。