学习模板trait

STL源码剖析里面的关于traits技术的描述很详细,这里将部分记录下来

struct input_iterator_tag{};
struct output_iterator_tag{};
struct forward_iterator_tag:public input_iterator_tag{};
struct bidirectional_iterator_tag:public forward_iterator_tag{};
struct random_access_iterator_tag:public bidirectional_iterator_tag{};


template<class Category,class T,class Distance=ptrdiff_t,
	class Pointer=T*,class Reference=T&>
	struct iterator{
		typedef Category iterator_category;
		typedef T 		 value_type;
		typedef Distance difference_type;
		typedef Pointer pointer;
		typedef Reference reference;
	};

	template <class Iterator>
	struct iterator_traits{
		typedef typename Iterator::iterator_category iterator_category;
		typedef typename Iterator::value_type value_type;
		typedef typename Iterator::difference_type difference_type;
		typedef typename Iterator::pointer pointer;
		typedef typename Iterator::reference reference;
	};

	template <class T>
	struct iterator_traits<T*>{
		typedef random_access_iterator_tag 	iterator_category;
		typedef T 							value_type;
		typedef ptrdiff_t 					difference_type;
		typedef T*							pointer;
		typedef T&							reference;
	};

	template <class T>
	struct iterator_traits<const T*>{
		typedef random_access_iterator_tag 	iterator_category;
		typedef T 							value_type;
		typedef ptrdiff_t 					difference_type;
		typedef const T*					pointer;
		typedef const T&					reference;
	};


	template <class Iterator>
	inine typename iterator_traits<Iterator>::iterator_category
	iteratorCategory(const Iterator&)
	{
		typedef typename iterator_traits<Iterator>::iterator_category category;
		return category();
	}

	template<class InputIterator,class Distance>
	inline void __advance(InputIterator& i,Distance n,input_iterator_tag){
		while(n--)++i;
	}

	template<class BidirectionalIterator,class Distance>
	inline void __advance(BidirectionalIterator& i,Distance n,bidirectional_iterator_tag){
		if(n>=0)
			while(n--)++i;
		else
			while(n++)--i;
	}

	template <class RandomAccessIterator,class Distance>
	inline void __advance(RandomAccessIterator& i,Distance n,random_access_iterator_tag){
		i += n;
	}

	template<class InputIterator,class Distance>
	inline void advance(InputIterator& i,Distance n){
		__advance(i,n,iteratorCategory(i));
	}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tianminghahaha/article/details/49904599
文章标签: stl traits
个人分类: C++ win32 C++
上一篇在android studio上使用小米真机调试
下一篇android活动的启动模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭