Effective C++ Item 48 认识 template 元编程
来源:互联网 发布:a3两厢好还是三厢 知乎 编辑:程序博客网 时间:2024/06/07 22:42
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:Template metaprogramming (TMP, 模板元编程)可将工作由运行期移往编译期,因而得以实现早期错误侦测和更高的执行效率
示例1:
template<typename IterT, typename DistT>void advance(IterT &iter, DistT d){if(typeid(typename std::iterator_traits<IterT>::iterator_catogory) == typeid(std::random_access_iterator_tag)){iter += d;}else{if(d >= 0) { while(d--) ++iter;}else {while(d++) --iter;}}}std::list<int>::iterator iter;advance(iter, 10); //当这里调用时,将会具体化出下面的函数void advance(std::list<int>::iterator &iter, int d){if(typeid(typename std::iterator_traits<std::list<int>::iterator>::iterator_catogory) == typeid(std::random_access_iterator_tag)){iter += d; //编译出错。因为 std::list<int>::iterator 不支持 += }else{if(d >= 0) { while(d--) ++iter;}else {while(d++) --iter;}}}
解析:虽然不会执行 += 那一行,但编译器必须确保所有源码都有效。
纠正:融合重载技术后,traits classes 有可能在编译期对类型执行 if...else 测试 --> 见 Item 47
示例2:TMP主要是个函数式语言,主要涉及递归模板具体化
template<unsigned n>struct Factorial{enum {value = n * Factorial<n-1>::value }; //enum hack, 声明一个名为 value 的 TMP 变量来保存当前计算所得的阶乘值 };template<> //全特化。 当 Factorial<0> 的值是1struct Factorial<0>{enum {value = 1};};int main(){std::cout << Factorial<5>::value;}
0 0
- Effective C++ Item 48 认识 template 元编程
- 《Effective C++》:条款48:认识template元编程
- C++之认识template元编程(48)---《Effective C++》
- 《Effective C++》读书笔记之item48:认识template元编程
- [翻译] Effective C++, 3rd Edition, Item 48: 感受 template metaprogramming(模板元编程)
- Effective C++ 条款 48:认识template元编程
- 条款48:认识template元编程
- 条款48:认识template元编程
- 通过factorial认识template元编程
- 条款48:认识template元编
- C++template元编程学习心得--数据类型
- C++template元编程学习心得-switch结构
- <Effective Mordern C++>笔记:Item 1: Understand the template type deduction.
- Item 48:了解模板元编程
- 《Effective C#》Item 9:区别和认识四个判等函数
- 《Effective C#》Item 9:区别和认识四个判等函数
- 《Effective C#》Item 9:区别和认识四个判等函数
- 《Effective C#》Item 9:区别和认识四个判等函数
- 关于Android的nodpi,xhdpi,hdpi,mdpi,ldpi
- SparseArray浅析
- 2014北邮新生归来赛解题报告d-e
- ubuntu 更改文件和文件夹权限
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 07 Control Flow
- Effective C++ Item 48 认识 template 元编程
- SDN驱动云数据中心的发展
- maven的jar包的查询地址
- git 修改远程仓库 remote origin
- IOS 判断应用版本和升级提示
- Eclipse常用配置
- jQuery hover事件 parent和parents
- 浅谈msp430f5529入门(3)——定时器A/Timer_A
- 寒城攻略:Listo 教你 25 天学会 Swift 语言 - 08 Functions