이 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 타입 이전의 타입 - 등등.
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 > {
};
하거나 매크로를 사용하여 : : <number of numeric types>^2
꽤 큰 숫자 때문에
#define max(l,r) ((l) >= (r) ? (l) : (r))
훨씬 간단을, 그렇지?C와
'double' 또는'int'에 암시 적으로 캐스트하기 때문에 잘못되었습니다. 표준 유형에 대한 특수 버전을 작성할 수 있습니다. –
std :: max의 문제점은 무엇입니까? – Moritz
@ 모리츠, 질문은 최대 2 개의 숫자를 찾는 방법에 관한 것이 아닙니다. – cppcoder