为什么要有traits编程技巧
我现在接触的还比较少,我感觉traits的作用就相当于一个提取类型的机器,然后都统一为一个类型,似的相同的逻辑不因为类型问题而出现大量的冗余代码,下面是一个简单的例子。
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class TypeTraits
{
public:
typedef T ReturnType;
};
template <>
class TypeTraits<int>{
public:
typedef int ReturnType;
};
template <>
class TypeTraits<double >{
public:
typedef double ReturnType;
};
template <typename T, typename TypeTraits=TypeTraits<T>>
typename TypeTraits::ReturnType average_x(const T *begin, const T *end)
{
typename TypeTraits::ReturnType total = 0;
int count = 0;
while (begin != end)
{
total += * begin;
++begin;
++count;
}
return total / count;
}
void test_average()
{
double a[] = {1, 2.1, 3, 4, 5};
cout<<average_x<double>(a, a+5)<<endl;
double b[] = {1, 2, 3, 4, 5};
cout<<average_x<double>(b, b+5)<<endl;
}
int main()
{
test_average();
}