Overload resolution of template functions

后端 未结 3 1885
渐次进展
渐次进展 2020-12-30 06:23

Consider this code:

#include 

//Number1
template
auto max (T1 a, T2 b)
{
    std::cout << \"auto max(T         


        
3条回答
  •  失恋的感觉
    2020-12-30 07:10

    For each of your function calls the compiler has 2 functions to choose from and chooses the best one. Unknown template parameters are deduced from the arguments apart from RT which must be explicitly specified and can't be deduced.

    auto a = ::max(4, 7.2);
    

    As RT is not specified and can't be deduced, the second overload is not usable so is ignored. The first is chosen and the types are deduced as int and double.

    auto b = ::max(4, 7.4);
    

    RT is now specified so the compiler can choose to either use max or max, the argument types for the 3 template parameter version match the function arguments exactly whereas the 2 template parameter version would require a cast from int to double so the 3 parameter overload is chosen.

    auto c = ::max(7, 4.);
    

    RT is now specified so the compiler can choose to either use max or max, the argument types both functions are now the same so the compiler can't choose between them.

提交回复
热议问题