Template argument deduction of return type

Viewed 111

How is the return type here being deduced? In other words, how based on the return type of the function pointer does it instantiate the correct function.

template<typename From, typename To>
To Convert(const From& f) 
{
    std::cout << sizeof(From) << " " << sizeof(To) << std::endl;    
    return To(f);
}



int main()
{
    float (*p)(const double &e) = Convert;
    p(20.2);

}

This prints

8 4
1 Answers

It's true that return types cannot be deduced in a function call even if there is context that could be used:

template<class T> T get();
struct X {} x=get();  // error: cannot deduce T

No type except (reference to) cv X could work here, but you just don't consider that it is exactly the initializer of a variable.

However, return types can be deduced when a function is named in a context where a particular type is "obviously" expected, as in the question, as well as when conversion function templates are used (since there's nothing else to deduce).

Related