码迷,mamicode.com
首页 > 其他好文 > 详细

Traits技法

时间:2017-11-01 01:00:48      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:迭代器   log   特化   ret   temp   turn   pen   trait   typedef   

扮演“特性萃取机”角色,萃取各个迭代器的特性(迭代器的相应类型)

通过class template partial specialization的作用,不论是原生指针或class-type iterators,都可以让外界方便地取其相应类别

  

#pragma once

template <class T>
class MyIter
{
public:
	MyIter(T *p = 0):ptr(p){}
	MyIter(MyIter<T> &ths):ptr(ths.ptr){}
	T& operator*(){return *ptr;}

	typedef T value_type;

private:
	T *ptr;	
};


// Partial Specialization 偏特化
template <class T>
struct iterator_traitse
{
	typedef typename T::value_type value_type;
};

template <class T>
struct iterator_traitse<T *>
{
	typedef T value_type;
};

template <class T>
typename iterator_traitse<T *> :: value_type fun(T ite)
{
	return *ite;
}

int main()
{
	MyIter<int> ite(new int(8));
	
	// cannot convert from ‘MyIter<T>‘ to ‘int‘
	int n = fun(ite);

	return 0;
}

 

Traits技法

标签:迭代器   log   特化   ret   temp   turn   pen   trait   typedef   

原文地址:http://www.cnblogs.com/xiaobingqianrui/p/7764532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!