STL学习杂记

 // function template 参数推到机制
template<class I, class T>
void func_impl(I iter, T t)
{
	T tmp;	//T 迭代器所指类型
	//func() 工作
};

template<class T>
inline void func(I iter)
{ 
	func_impl(iter, *iter); // func 的工作全部移到 func_impl 中
}


template<class T>
struct MyIter
{
	typedef T value_type;  //嵌套类型宣告( nested type)
	T* ptr;
	MyIter(T* p = 0) : ptr(p){}
	T& operator*() const {return *ptr;}
};

template<class T>
typename I::value_type //作为 func 的返回值类型 直接把类型给定义出来

//typename 告诉编译器在编板参数具体化之前 I::value_type 是个类型,否则无法通过编译
func(I ite)
{ return *ite;}


//模板参数的偏特化 对多个模板参数的个别参数进行特化
//对template 参数更进一步的条件限制,所设计出来的一个特化的模板类(依然是泛型化的类)

// traits  的意义是:
// 如果 I 定义有自己的 value type, 那么透过这个 traits 的作用,萃取出来的value type 就是 I::value_type

//如果 I 定义有自己的value类型 可以直接 通过 trait提取出 I  的value类型使用

template<class I>
typename iterator_traits<I>::value_type //作为返回值类型

//traits的偏特化

template<class T>
struct iterator_traits<T*> {  //偏特化版, 迭代器是原生指针

	typedef T value_type;
};

//于是 原生指针 int* 虽然不是一种class type,亦可透过 traits取其 value type

struct iterator_traits<const T*> {  //偏特化版, 把const 指针的类型 T萃取出来的特化版

	typedef T value_type;
};

//迭代器的响应型别(associated types)
// value_type 
// difference_type 
// pointer 
// reference 
// inerator_category

template<class I>
struct iterator_traits {

	typedef typename I::iterator_category iterator_category;
	typedef typename I::value_type value_type;
	typedef typename I::difference_type difference_type;
	typedef typename I::pointer pointer;
	typedef typename I::reference reference;
}

// iterator_traits需要对传入型别是 原生指针 或 原生 const 指针设计特化版本

//迭代器相应型别:: difference_type
//表示两个迭代器之间的距离,

template<class I, class T>
typename iterator_traits<I>::difference_type //萃取的类型作为函数返回值

count (I first, I last, const T& value) {
	typename iterator_traits<I>::difference_type n = 0;
	for (; first != last; ++first)
		if (*first == value)
			++n;
	return n;
}

//针对原生指针的特化版本
template<class T>
struct iterator_traits<T*> {
	....
	typedef ptrdiff_t difference_type;
};

//针对原生指针是 const pointer 设计的特化版本
template<class T>
struct iterator_traits<const T*> {
	....
	typedef ptrdiff_t difference_type;
};

// reference type
// 迭代器所指对象允许改变,提取的是一个左值,右值不允许赋值动作


//从STL提供的 迭代器类继承
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 Didtance difference_type;
	typedef pointer pointer;
	typedef Reference reference;
}

//继承STL的迭代器类
template<class Item>
struct ListIter : public std::iterator<std::forward_iterator_tag, Item>
{...}

// traits 技术 大量使用在STL中,它利用嵌套类型的技巧与编译程序的模板参数推导功能;
// 补充C++未提供的型别认证方面的缺陷与C++非强型语言的遗憾。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值