#include <iostream>
using std::cout;
using std::endl;
//归根到底就是使用了function template的参数推导机制(argument deduction)
//traits函数 生成一个该类型的临时对象,然后返回该对象
//而真正的调用函数根据临时对象的类型决定调用哪个函数,当然这些函数是重载的,只是根据类型不同调用不同的重载函数而已
//
//
//
//迭代器的类型,某些函数根据其类型选择迭代方式
struct input_iter {};
struct forward_iter : public input_iter {};
struct random_access_iter : public forward_iter {};
template<class Category,
class T,
class Distance = ptrdiff_t,
class Pointer = T*,
class Reference = T&>
class iter
{
typedef Category iterator_category; //迭代器的类型
typedef T value_type; //迭代器中的值的类型
typedef Distance difference_type; //
typedef Pointer pointer;
typedef Reference reference;
};
//根据Iterator萃取其类型
template<class Iterator>
struct iter_traits
{
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::distance_type distance_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
};
//针对原生指针(naive pointer)的traits的偏特化版
template <class T>
struct iter_traits<T*>
{
typedef random_access_iter iterator_category; //原生指针应该是随机存取的迭代器
typedef T value_type;
typedef ptrdiff_t distance_type;
typedef T* pointer;
typedef T& reference;
};
template <class T>
struct iter_traits<const T*>
{
typedef random_access_iter iterator_category;
typedef T value_type;
typedef ptrdiff_t distance_type;
typedef T* pointer;
typedef T& reference;
};
//根据Iterator获取其迭代器类型
template <class Iterator>
inline typename iter_traits<Iterator>::iterator_category iter_category(const Iterator&)
{
typedef typename iter_traits<Iterator>::iterator_category category;
return category();
}
//根据Iterator获取其迭代器中值的类型
template <class Iterator>
inline typename iter_traits<Iterator>::value_type* iter_value_type(const Iterator&)
{
return static_cast<typename iter_traits<Iterator>::value_type*>(0);
}
class A {};
void fun(int *a)
{
cout << "int *a " << endl;
}
void fun(A *a)
{
cout << "class A" << endl;
}
int main()
{
A *pa = new A;
int *a = 0;
fun(iter_value_type(pa));
fun(iter_value_type(a));
return 0;
}
STL源码剖析中 traits的使用
最新推荐文章于 2024-10-07 07:00:00 发布