简体   繁体   中英

Converting a Functor to an Object of Type function

Say I have this function:

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

This is legal code :

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

foo(op, 13, 42);

But when I do this:

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

I get the error:

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

Why can I initialize an object of type function<int(const int&, const int&)> from plus<int>() but I cannot pass plus<int>() into an parameter of type function<T(const T&, const T&)> ? Is it something having to do with the template?

Quoting from the Standard section 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.

This does not work in your case because the template parameters have not been provided explicitly. The compiler needs to do a deduction. Thus as per the above, it will not do the implicit conversion from functor to std::function .

So, you can do (As mentioned by @flatmouse in the comment):

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

This works because there is no template argument deduction that needs to be performed since all the template parameters are explicitly specified. And as per the above quote from standard, the implicit conversion should work for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM