类模板的公有数据类型成员
在类中使用typedef定义一个已知类型的别名,类模板的这种公有类型就成为类外模块的类型资源,从而是外部模块可以用这些公有类型来设计程序并在类模板之间进行功能上的协作
template<typename T1,typename T2>
class MyTraits{
public:
typedef T1 my_type1;//定义了一个公有类型
private:
typedef T2 my_type2;//定义了一个私有类型
};
int _tmain(int argc, _TCHAR* argv[])
{
typename MyTraits<int, double>::my_type1 a = 10;
//typename MyTraits<int, double>::my_type2 b = 5.5;私有类型不能直接访问
return 0;
}
数据类型表
如果一个类模板中的所有成员都是公有数据类型,那么相对于嵌入式数据类型表,这个类模板就叫作独立数据类型表
template<typename T1,typename T2>
class MyTraits{
public:
typedef T1 my_type1;
typedef T1& reference1;
typedef T2 my_type2;
typedef T2& reference2;
};
template<typename T1,typename T2>
class A :public MyTraits<T1, T2>
{
//A继承类Mytraits,A也能使用其中的公有数据类型
};
int _tmain(int argc, _TCHAR* argv[])
{
typename A<int, double>::my_type1 a = 10;
typename A<int, double>::my_type2 b = 10.9;
typename A<int, double>::reference1 c = a;
typename A<int, double>::reference2 d = b;
return 0;
}
独立数据类型表可以用来规范派生类模板类型发布
特化数据类型表
特化类模板中形成的数据类型表
//下面这两个类可以写成一个模板类,提供三个模板参数,这里为其分别提供一个特化数据类型表
class Test1{
public:
char compute(int x, double y)
{
return x;
}
};
class Test2{
public:
double compute(double x, double y)
{
return x;
}
};
template<typename T>
class MyTraits{
};
//特化数据类型表1
template<>
class MyTraits<Test1>{
public:
typedef int par1;
typedef double par2;
typedef char ret;
};
//特化数据类型表2
template<>
class MyTraits<Test2>{
public:
typedef double par1;
typedef double par2;
typedef double ret;
};
//把test1和test2的功能写在了一起,且可以通过类名调用对应的特化数据类型表来执行不同的操作
template<typename T>
class Test{
public:
typename MyTraits<T>::ret compute(typename MyTraits<T>::par1 x, typename MyTraits<T>::par2 y)
{
return x;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test<Test1> t1;
cout << t1.compute(5, 6.2) << endl;
Test<Test2> t2;
cout << t2.compute(5.2, 6.2) << endl;
return 0;
}
用Matrits一个类来提供所有数据类型的接口
template<typename T>
class MaTraits{
public:
typedef T value_type;
typedef T* pointer;
typedef T& reference;
};
template<typename T>
class MaTraits<T*>{
public:
typedef T value_type;
typedef T* pointer;
typedef T& reference;
};
int _tmain(int argc, _TCHAR* argv[])
{
MaTraits<int>::value_type a = 10;
MaTraits<double>::value_type b = 15;
MaTraits<int*>::pointer fa = &a;
cout << *fa << endl;
return 0;
}