Traits技术
- traits=特性
提取不同类的共性,统一处理
依靠显示模板特殊化,把代码中因不同类型发生变化的片段提取出,用统一的接口来包装
接口可以为c++类所能包含的任何东西
客户通过traits模板类公开的接口来间接访问
- 代码示例
#include <iostream>
using namespace std;
class CIntArray
{
public:
CIntArray();
~CIntArray(){}
int GetSum(int times);
private:
int m_a[10];
};
CIntArray::CIntArray()
{
for (int i = 0; i < 10; i++) {
m_a[i] = i + 1;
}
}
int CIntArray::GetSum(int times)
{
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += m_a[i];
}
return sum * times;
}
class CFloatArray
{
public:
CFloatArray();
~CFloatArray(){}
float GetSum(float times);
private:
float m_a[10];
};
CFloatArray::CFloatArray()
{
for (int i = 0; i < 10; i++) {
m_a[i] = i + 1;
}
}
float CFloatArray::GetSum(float times)
{
float sum = 0.0;
for (int i = 0; i < 10; i++) {
sum += m_a[i];
}
return sum * times;
}
// traist模板类
template<class T>
class NumTraits {};
//模板类特殊化
template<>
class NumTraits<CIntArray>
{
public:
typedef int resultType;
typedef int inputPara;
};
//模板类特殊化
template<>
class NumTraits<CFloatArray>
{
public:
typedef float resultType;
typedef float inputPara;
};
//对外接口
template<class T>
class CApply
{
public:
typedef typename NumTraits<T>::resultType result;
typedef typename NumTraits<T>::inputPara input;
result GetSum(T& obj, input in)
{
return obj.GetSum(in);
}
};
int main()
{
CIntArray cInt;
CApply<CIntArray> ci;
std::cout << ci.GetSum(cInt, 3) << std::endl;
CFloatArray cFloat;
CApply<CFloatArray> cf;
std::cout << cf.GetSum(cFloat, 5.5) << std::endl;
return 0;
}