Overload resolution of template functions

后端 未结 3 1892
渐次进展
渐次进展 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:15

    the template argument deduction does not take the return type into account,

    Yes. Template argument deduction is performed based on function arguments.

    so why max is ambiguous and not max?

    Given ::max(7, 4.), for the 1st overload, the 1st template parameter T1 is specified as int, and T2 is deduced as double from the 2nd function argument 4., then the instantiation would be double max(int, double). For the 2nd overload, the 1st template parameter RT is specified as int, T1 is deduced as int from 7, T2 is deduced as double from 4., then the instantiation would be int max(int, double). Overload resolution doesn't consider return type too, the two overloads are both exact match and then ambiguous.

    Given ::max(7, 4.), for the 1st overload, the 1st template parameter T1 is specified as double, and T2 is deduced as double from 4., so the instantiation would be double max(double, double). For the 2nd overload, the 1st template parameter RT is specified as double, T1 is deduced as int from 7, T2 is deduced as double from 4., then the instantiation would be double max(int, double). Then the 2nd overload wins in overload resolution because it's an exact match, the 1st one requires the implicit conversion from int to double for the 1st argument 7.

提交回复
热议问题