traits技术利用显示模板特殊化来把代码中因类型不同而发生变化的片段拖出来,用统一的接口来包装。traits就像是特性的提取工具,提取不同类的共同特性,以便统一处理。
下面以一个例子说明此技术
#include <iostream>
#include <cstdlib>
using namespace std;
class CIntAry
{
int arr[10];
public:
CIntAry()
{
for(int i = 0; i < 10; i++)
{
arr[i] = i + 1;
}
}
int getSum(int times)
{
int sum = 0;
for(int i = 0; i< 10; i++)
{
sum += arr[i];
}
return sum * times;
}
};
class CFltAry
{
float arr[10];
public:
CFltAry()
{
for(int i = 0; i < 10; i++)
{
arr[i] = 1.0f / (i+1);
}
}
float getSum(float times)
{
float sum = 0;
for(int i = 0; i< 10; i++)
{
sum += arr[i];
}
return sum * times;
}
};
template <class T>
class NumTraits
{
};
template <>
class NumTraits<CIntAry>
{
public:
typedef int result;
typedef int inpara;
};
template <>
class NumTraits<CFltAry>
{
public:
typedef float result;
typedef float inpara;
};
template <class T>
class CApply
{
public:
typedef typename NumTraits<T>::result res;
typedef typename NumTraits<T>::inpara in;
res getSum(T &obj,in inpara)
{
return obj.getSum(inpara);
}
};
int main(int argc, char **argv)
{
CIntAry intary;
CFltAry fltary;
int a = atoi(argv[1]);
float b = atof(argv[2]);
CApply<CIntAry> c1;
CApply<CFltAry> c2;
cout << "整数数组和的argv[1]倍是: " << c1.getSum(intary, a) << endl;
cout << "浮点数组和的argv[2]倍是: " << c2.getSum(fltary, b) << endl;
}