模版特化

来源:互联网 发布:php如何建站 编辑:程序博客网 时间:2024/05/08 10:52

最近在看STL源代码时候发现很多东西值得学习, 需要不断消化, 应用在平时项目中, 一个简单的模版萃取方法, 在STL里面应用也很广.

 

#include <iostream>

using namespace std;

template <class T>
struct Traits
{
  typedef T type_name;
};

template <class T> struct Traits<T *>
{
  typedef T type_name;
};

template <class T> struct Traits<const T *>
{
  typedef T type_name;
};

template <class T>
class Iterator
{
public:

  typedef typename Traits<T>::type_name type_name;

  Iterator(type_name * pointor) : m_pointor(pointor)
  {
  }

  type_name & operator* () const
  {
    return *m_pointor;
  }

private:
  type_name *m_pointor;
};

template <class T>
typename T::type_name testFunc(T itr)
{
  return *itr;
}

int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused)))
{
  Iterator<const int *> itr(new int(10));
  cout << testFunc(itr) << endl;

  Iterator<int * > itr2(new int(11));
  cout << testFunc(itr2) << endl;
}