Effective C++ 条款 48:认识template元编程

来源:互联网 发布:供应链协同软件 编辑:程序博客网 时间:2024/06/03 18:46

(一)

template metaprogramming(模板元编程)是编写template-based c++程序并执行于编译期的过程。是以c++写成,执行于c++编译器内的程序。一旦TMP程序执行结束,其输出,也就是template具现出来的若干c++源码,便会一如往常的编译。

条款47指出,advance那个typeid-based解法的效率比traits解法低,因为此方案中,1.类型测试发于运行期而非编译器,2。运行期类型测试代码会出现在可执行文件中。traits解法就是tmp,它引发“编译期发生于类型身上的if。。。else计算。

advance的typeid-based实现方式可能导致编译期问题:

std::list<int>::iterator iter; advance(iter, 10);//无法通过编译
下面是这一版advance针对上述调用而产生的:
void advance(std::list<int>::iterator& iter, int d) {     if (typeid(std::iterator_traits<std::list<int>::iterator>::iterator_category)        == typeid(std::random_access_iterator_tag))     {         iter += d;                //wrong!     }     else         ... }
list<int>::iterator是bidirectional不支持+=。我们知道绝不会执行+=那一行,但是编译器必须确保所有源码都有效,纵使是不会执行的代码
所以我们要用TMP,而不要用typeid-based。

(二)

让我们看看循环,tmp藉由递归完成。

template<unsigned n> struct Factorial{                            //一般情况     enum{value = n*Factorial<n-1>::value}; };template<> struct Factorial<0>{                //特殊情况     enum{value = 1}; };

tmp递归并不涉及递归函数调用,而是涉及“递归模板具现化”(recursive template instantiation)。


请记住:

(1)Template metaprogramming(TMP,模版元编程)可将工作由运行期移往编译期,因为得以实现早期错误侦测和更高的执行效率。

(2)TMP可被用来生成“基于政策选择组合”的客户定制代码,也可用来避免生成对某些函数类型并不适合的代码。





0 0
原创粉丝点击