欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c/c++ 模板与STL小例子系列<三> traits

程序员文章站 2022-07-02 13:56:59
c/c++ 模板与STL小例子系列 traits 对这个概念,还是处于懵逼的状态,初步体会就是,为了解决类型之间的转换问题。 从一个类型为A的指针,转化到类型为B的指针,中间需要用void 来作为中介。traits好像可以解决这种问题。 下面弄了3个小例子,可以初步感受一下。 例子1: ......

c/c++ 模板与stl小例子系列<三> traits

对这个概念,还是处于懵逼的状态,初步体会就是,为了解决类型之间的转换问题。

从一个类型为a的指针,转化到类型为b的指针,中间需要用void*来作为中介。traits好像可以解决这种问题。

下面弄了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();
}