正在学习STL源码,看到了traits编程技术,于是上网查了查,发现不用每次都定义类
比如:
/*特性萃取器*/ template <class unknown_class> struct unknown_class_traits { typedef typename unknown_class::return_type return_type; }; /*特性萃取器 —— 针对原生指针*/ template <class T> struct unknown_class_traits<T*> { typedef T return_type; }; /*特性萃取其 —— 针对指向常数*/ template <class T> struct unknown_class_traits<const T*> { typedef const T return_type; };
c++中已经有iterator_traits类,可以直接用,代码如下
#include <iostream> #include <typeinfo> #include <iterator> #include <vector> using namespace std; class A { public: A(int i=10) { k=i; } private: int k; }; template<class it>//pointer and value_type and reference void fun(it) { typedef typename iterator_traits<it>::pointer pointer; cout<<"pointer:"<<typeid(pointer).name()<<endl; typedef typename iterator_traits<it>::value_type value_type; cout<<"value_type:"<<typeid(value_type).name()<<endl; typedef typename iterator_traits<it>::reference reference; cout<<"reference:"<<typeid(reference).name()<<endl; } template<class it>//iterator_category and difference_type void func(it t1,it t2) { typedef typename iterator_traits<it>::iterator_category iterator_category; cout<<"iterator_category:"<<typeid(iterator_category).name()<<endl; typedef typename iterator_traits<it>::difference_type difference_type; cout<<"difference_type:"<<typeid(difference_type).name()<<endl; } int main( ) { A *a=new A(6); fun(a); vector<int> vec(10); func(vec.begin(),vec.end()); return 0; }
msdn上的代码:
// iterator_traits.cpp // compile with: /EHsc #include <iostream> #include <iterator> #include <vector> #include <list> using namespace std; template< class it > void function( it i1, it i2 ) { iterator_traits<it>::iterator_category cat; cout << typeid( cat ).name( ) << endl; while ( i1 != i2 ) { iterator_traits<it>::value_type x; x = *i1; cout << x << " "; i1++; }; cout << endl; }; int main( ) { vector<char> vc( 10,'a' ); list<int> li( 10 ); function( vc.begin( ), vc.end( ) ); function( li.begin( ), li.end( ) ); } \* Output: struct std::random_access_iterator_tag a a a a a a a a a a struct std::bidirectional_iterator_tag 0 0 0 0 0 0 0 0 0 0 *\
msdn链接:https://msdn.microsoft.com/zh-cn/library/zdxb97eh.aspx