手机版
你好,游客 登录 注册
背景:
阅读新闻

C++模板元编程的两个例子

[日期:2012-08-27] 来源:Linux社区  作者:aheroofeast [字体:大 中 小]
C++模板元编程,是使用template进行编译期运算的一种机制,可以认为是C++的一种编程方式。

第一个例子:计算整数N的阶乘。

  1. //模板的一般形式   
  2. template<int N>  
  3. class Factorial  
  4. {  
  5. public:  
  6.     enum  
  7.     {  
  8.         _result = N * Factorial<N-1>::_result  
  9.     };  
  10. };  
  11.   
  12. //用于结束递归规则的特化模板   
  13. template<>  
  14. class Factorial<0>  
  15. {  
  16. public:  
  17.     enum  
  18.     {  
  19.         _result = 1  
  20.     };  
  21. };  
  22.   
  23. int main()  
  24. {  
  25.     const int Num = 10;  
  26.     cout << Num << "! = " << Factorial<Num>::_result << endl;  
  27. }  

运行结果:10! = 3628800

其中的思考方式,我感觉是数学归纳法的应用。注意模板在其中起的作用,在编译期,编译器使用template生成了class Factorial<0>……class Factorial<10>一共11个class定义,在程序运行时其实计算过程并没有占用CPU时间,只不过这么多class的定义占用了一些内存。

第二个例子:编译期的if语句

这是 Bjarne Stroustrup在《Evolving a language in and for the real world C++ 1991-2006》一文中举的例子。

  1. struct T_Left  
  2. {  
  3.     int value;  
  4. };  
  5. struct T_Right  
  6. {  
  7.     char value;  
  8. };  
  9.   
  10. template<bool b, class X, class Y>  
  11. struct if_  
  12. {  
  13.     typedef X type; // use X if b is true   
  14. };  
  15. template<class X, class Y>  
  16. struct if_<false, X, Y>  
  17. {  
  18.     typedef Y type; // use Y if b is false   
  19. };  
  20.   
  21.   
  22. int main()  
  23. {  
  24.     cout << "Type Size = " << sizeof(if_<sizeof(T_Left) < 4, T_Left, T_Right>::type) << endl;  
  25. }  
其实也是根据编译期能确定的值,来进行编译期的选择。

模板元编程的应用包括:Blitz++库;boost::mpl库;以及《Modern C++ Design》一书中提到的typelist。

linux
相关资讯       C++ 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款