浅析STL中function template的参数推导机制(argument deduction)——以插入排序为例
?STL的中心思想就是将容器和算法分开,分别独立设计和泛型化,然后通过迭代器来连接算法和容器。容器和算法利用C++ 中class template和function template机制来泛型化。设计STL的算法时,传递过来的参数往往是迭代器类型的参数,迭代器引用的容器数据类型当前是不确定的(template是在编译时确定数据类型的),当算法中需要利用迭代器所指对象的类型来定义或声明变量时,就会出现小小的困扰,因为C++中没有提供提取对象数据类型的操作(即使利用RTTI性质中的typied()来获取类型名,也不能用来做变量声明和定义之用)。这时我们就需利用function template的参数推导机制。下面举个简单例子来详细讨论一下:
//STL版本template<class I, class Cmp>void insertSort(const I& begin, const I& end, Cmp lessThan);template <class I, class T>void _insertSort(const I& begin, const I& end, const T t);template<class I, class T, class Cmp>void _insertSort(const I& begin, const I& end, Cmp lessThan, const T& t);template <class I>void insertSort(const I& begin, const I& end){if(begin != end)_insertSort(begin, end, *begin); //这里要取begin所指向的值,避免越界,所以先判断}template <class I, class T>void _insertSort(const I& begin, const I& end, const T t){insertSort(begin, end, less<T>()); // 双参数调用三参数,less<T>中的类型也利用参数推导获取}template<class I, class Cmp>void insertSort(const I& begin, const I& end, Cmp lessThan){if(begin != end)_insertSort(begin, end, lessThan, *begin);}//算法的具体实现template<class I, class T, class Cmp>void _insertSort(const I& begin, const I& end, Cmp lessThan, const T& t){I j;for(I i = begin+1; i != end; ++i){T tmp = *i; //通过参数推导确定T类型for(j = i; j != begin && lessThan(tmp, *(j-1)); --j)*j = *(j-1);*j = tmp;}}?
上面就是个人对参数推导机制的粗浅理解,要深入了解迭代器指向对象的类型可参考《STL源码剖析》,以上代码来自于下面参考文献。代码都经过调试,可以正常运行。这里做一个学习过程的标记。
?