这是 C++03 的答案。对于 C++11 - 使用 auto/decltype (请参阅其他答案)。
您必须创建另一个模板template CommonNumericType<T1,T2>
::
template <typename L, typename R>
typename CommonNumericType<T1,T2>::Type max(L x, R y)
{
return x>y ? x : y;
}
并将这个 CommonNumericType 专门用于每对可能的数字类型:
template <typename L, typename R>
struct CommonNumericType;
template <typename T>
struct CommonNumericType<T,T> {
typedef T Type;
};
template <typename L>
struct CommonNumericType<L,long double> {
typedef long double Type;
};
template <typename R>
struct CommonNumericType<long double,R> {
typedef long double Type;
};
// ...
template <>
struct CommonNumericType<int,short> {
typedef int Type;
};
// and many others stuff
我可以考虑创建一些数字类型的层次结构——浮点类型在 int 类型之前——等等。因为<number of numeric types>^2
是相当大的数字:
template <typename T>
struct NumericTypeOrder;
template <>
struct NumericTypeOrder<long double> { enum { VALUE = 1 }; };
template <>
struct NumericTypeOrder<double> { enum { VALUE = 2 }; };
template <>
struct NumericTypeOrder<float> { enum { VALUE = 3 }; };
template <>
struct NumericTypeOrder<unsigned long long> { enum { VALUE = 4 }; };
// etc for all numeric types - where signed char is last one...
template <typename L, typename R, bool L_bigger_than_R>
struct CommonNumericTypeImpl;
template <typename L, typename R>
struct CommonNumericTypeImpl<L,R,true> {
typedef L type;
};
template <typename L, typename R>
struct CommonNumericTypeImpl<L,R,false> {
typedef R type;
};
template <typename L, typename R>
struct CommonNumericType
: CommonNumericTypeImpl<L,R,NumericTypeOrder<L>::value >= NumericTypeOrder<R>::value > {
};
或者只使用宏:
#define max(l,r) ((l) >= (r) ? (l) : (r))
简单多了,不是吗?