模板特化

From: http://blog.csdn.net/wuzhekai1985/article/details/6654667

#include <iostream>
#include <vector>
#include <list>
using namespace std;

//萃取剂
template<class I>
struct Iterator_traits{
    typedef typename I::value_type value_type;
};
//特化 原生指针
template<class T>
struct Iterator_traits<T*>{
    typedef T value_type;
};
//特化 原生常指针
template<class T>
struct Iterator_traits<const T*>{
    typedef T value_type;
};

#define VALUE_TYPE(I) Iterator_traits<I>::value_type()

//交换两个迭代器所指的元素
template <class Iter1, class Iter2>
inline void iter_swap(Iter1 a, Iter2 b) {
 _iter_swap(a, b, VALUE_TYPE(Iter1)); //VALUE_TYPE返回迭代器的值类型
}
//真正的交换函数
template <class Iter1, class Iter2, class T>
inline void _iter_swap(Iter1 a, Iter2 b, T) {
  T tmp = *a;
  *a = *b;
  *b = tmp;
}
//测试函数
int main()
{
    int a = 1, b = 2;
    iter_swap(&a,&b);
    cout<<a<<' '<<b<<endl;  //2 1
    
    list<int> l;
    l.push_back(3);
    l.push_back(4);
    iter_swap(l.begin(),++l.begin());
    cout<<*(l.begin())<<' '<<*(++l.begin())<<endl; //4 3

    Iterator_traits<int *>::value_type w = 5;       //特化
    Iterator_traits<const int*>::value_type  x = 6; //特化
        Iterator_traits<vector<int>::iterator>::value_type y = 7; //vector 容器
    Iterator_traits<list<int>::iterator>::value_type z = 8;   //list 容器
    cout<<w<<' '<<x<<' '<<y<<' '<<z<<endl; //5 6 7 8
    return 0;
}

 

posted @ 2014-08-11 08:07  anit_nait  阅读(145)  评论(0编辑  收藏  举报