@Andy 有正确的答案,效果很好。但是对于那些想要在 MyClass 被实例化为没有“长”值的类型时出现编译时错误的人,我将它与@SteveJessop 的优秀评论相结合以提供以下解决方案:
// --- Machinery to support double-precision 'T' to avoid overflow in method 'multiply' ---
// Note: uncomment typedef if don't want compile-time errors
// when no "long" type exists
// ----
template<typename T>
struct add_long { /*typedef T type;*/ };
template<> struct add_long<int8_t> { typedef int16_t type; };
template<> struct add_long<int16_t> { typedef int32_t type; };
template<> struct add_long<int32_t> { typedef int64_t type; };
template<> struct add_long<uint8_t> { typedef uint16_t type; };
template<> struct add_long<uint16_t> { typedef uint32_t type; };
template<> struct add_long<uint32_t> { typedef uint64_t type; };
template<> struct add_long<float> { typedef double type; };
template<> struct add_long<double> { typedef long double type; };
“longT”的示例用法:
template<class T> class MyClass
{
// Note: a compiler error on the next line means that
// class T has no double-precision type defined above.
typedef typename add_long<T>::type longT;
public:
longT multiply (T a, T b) { return longT(a) * b; }
}
MyClass 的示例用法:
MyClass<float> my;
printf("result = %lf\n", my.multiply(3.4e38, 3.4e38));