c/c++ 模板与STL小例子系列<三> traits
c/c++ 模板与STL小例子系列<三> traits
对这个概念,还是处于懵逼的状态,初步体会就是,为了解决类型之间的转换问题。
从一个类型为A的指针,转化到类型为B的指针,中间需要用void*来作为中介。traits好像可以解决这种问题。
通过traits技术,可以达到扔进去什么类型,给我吐出什么类型
扔进去的是int出来的t1也是int类型
Iterator_1<int>::value_type t1 = 100;
下面弄了3个小例子,可以初步感受一下。
例子1:
#include <iostream>
using namespace std;
template<typename T, typename U>
class traits{
public:
typedef T value_type1;
typedef T& ref1;
typedef U value_type2;
typedef U& ref2;
};
template<typename TA, typename UA>
class A : public traits<TA, UA>
{
};
int main(){
A<int, double>::value_type1 a = 10;
A<int, double>::ref1 b = a;
cout << a << endl;
cout << b << endl;
A<int, double>::value_type2 a1 = 10.2;
A<int, double>::ref2 b1 = a1;
cout << a1 << endl;
cout << b1 << endl;
}
例子2:
#include <iostream>
using namespace std;
class Test1;
class Test2;
template<typename T>
class TypeTb1{};
template<>
class TypeTb1<Test1>{
public:
typedef char ret_type;
typedef int p1_type;
typedef double p2_type;
};
template<>
class TypeTb1<Test2>{
public:
typedef double ret_type;
typedef double p1_type;
typedef int p2_type;
};
template<typename T>
class Test{
public:
typename TypeTb1<T>::ret_type func(typename TypeTb1<T>::p1_t\
ype x,
typename TypeTb1<T>::p2_type y){
return x;
}
};
int main(){
Test<Test1> t;
cout << t.func(65, 6.18) << endl;
Test<Test2> t2;
cout << t2.func(6.18, 65) << endl;
}
例子3:
#include <iostream>
using namespace std;
class A{
public:
void show(){cout << "A show" << endl;}
};
template<typename T>
class Iterator_1{
public:
typedef T value_type;
typedef value_type* ptn;
typedef value_type& ref;
};
template<typename T>
class Iterator_2{
public:
typedef T value_type;
typedef value_type* ptn;
typedef value_type& ref;
};
template<typename T>
struct Traits{};
template<typename T>
struct Traits<T *>{
typedef T value_type;
typedef value_type* ptn;
typedef value_type& ref;
};
int main(){
Iterator_1<int>::value_type t1 = 100;
cout << t1 << endl;
Iterator_2<double>::value_type t2 = 1.23;
cout << t2 << endl;
Traits<double*>::value_type t3 = 4.45;
cout << t3 << endl;
Iterator_1<A>::ptn p;
p->show();
}