c ++模板-重载函数的多个实例与参数列表匹配
c++ template - More than one instance of overloaded function matches the argument list
为什么只有最后一次调用 max 引发错误?
error C2668: 'max': ambiguous call to overloaded function
#include <iostream>
#include <type_traits>
template<typename T1, typename T2>
auto max(T1 t1, T2 t2)
{
return t1 < t2 ? t2 : t1;
}
template<typename RT, typename T1, typename T2>
RT max (T1 a, T2 b)
{
return b < a ? a : b;
}
int main()
max<long double>(4.5, 4);
max<double>(4.5, 4);
return 0;
}
给定 max<long double>(4.5, 4);
,对于第一个 max
,它的第一个模板参数 T1
被指定为 long double
,T2
从 [=15= 推导出来] 为 int
。对于第二个 max
RT
指定为 long double
,T1
推导为 double
,T2
推导为 int
。然后第二个在重载解析中获胜,因为它是完全匹配,而第一个需要从 double
到 long double
.
的隐式转换
另一方面,给定max<double>(4.5, 4);
,第一个max
T1
被指定为double
,T2
被推导为int
.对于第二个 max
RT
指定为 double
,T1
推导为 double
,T2
推导为 int
。它们完全匹配。
为什么只有最后一次调用 max 引发错误?
error C2668: 'max': ambiguous call to overloaded function
#include <iostream>
#include <type_traits>
template<typename T1, typename T2>
auto max(T1 t1, T2 t2)
{
return t1 < t2 ? t2 : t1;
}
template<typename RT, typename T1, typename T2>
RT max (T1 a, T2 b)
{
return b < a ? a : b;
}
int main()
max<long double>(4.5, 4);
max<double>(4.5, 4);
return 0;
}
给定 max<long double>(4.5, 4);
,对于第一个 max
,它的第一个模板参数 T1
被指定为 long double
,T2
从 [=15= 推导出来] 为 int
。对于第二个 max
RT
指定为 long double
,T1
推导为 double
,T2
推导为 int
。然后第二个在重载解析中获胜,因为它是完全匹配,而第一个需要从 double
到 long double
.
另一方面,给定max<double>(4.5, 4);
,第一个max
T1
被指定为double
,T2
被推导为int
.对于第二个 max
RT
指定为 double
,T1
推导为 double
,T2
推导为 int
。它们完全匹配。