阅读stl源码剖析第三章,写了个traits例程, foo函数可以对iterator的类型做出推断,包括原生指针。
-
#include <iostream>
-
using namespace std;
-
template <typename T>
-
class MyIterator {
-
public:
-
typedef T value_type;
-
};
-
-
template <typename T>
-
class Traits {
-
public:
-
typedef typename T::value_type value_type;
-
};
-
-
template <typename T>
-
class Traits<T *> {
-
public:
-
typedef T value_type;
-
};
-
-
template <typename I>
-
void foo(I i) {
-
//typename means type, not member function
-
cout << "typeid = " << typeid(typename Traits<I>::value_type).name() << endl;
-
}
-
-
int main() {
-
MyIterator<char> mi;
-
MyIterator<string> ms;
-
int *pi = NULL;
-
foo(mi);
-
foo(ms);
-
foo(pi);
-
}
阅读(337) | 评论(0) | 转发(0) |