// traits 的应用 /////////////////////////////////////////// // traits template <typename T> class sigmaTraits {}; // 特化 template <> class sigmaTraits<char> { public: typedef int returnType; }; template <> class sigmaTraits<int> { public: typedef int returnType; }; template <> class sigmaTraits<float> { public: typedef double returnType; }; template <> class sigmaTraits<double> { public: typedef double returnType; }; /////////////////////////////////////////// #if 0 // char 溢出 template <typename T> inline T Sigma(const T const* start, const T const* end) { typedef T ReturnType; ReturnType s = ReturnType(); while (start != end) { s += *start++; } return s; } #endif // 1 #if 1 // 需要 trait 技术 template <typename T> inline typename sigmaTraits<T>::returnType Sigma(const T const* start, const T const* end) { typedef typename sigmaTraits<T>::returnType ReturnType; ReturnType s = ReturnType(); while (start != end) { s += *start++; } return s; } #endif // 1 int main() { // 需要 trait 技术才能保证计算结果正确。避免char溢出导致结果错误。 char str[] = "abc"; size_t len = strlen(str); char* pB = str; char* pE = str + len; printf("%d", Sigma(pB, pE)); }