歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++模板元編程的兩個例子

C++模板元編程的兩個例子

日期:2017/3/1 10:11:44   编辑:Linux編程
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. template<>
  13. class Factorial<0>
  14. {
  15. public:
  16. enum
  17. {
  18. _result = 1
  19. };
  20. };
  21. int main()
  22. {
  23. const int Num = 10;
  24. cout << Num << "! = " << Factorial<Num>::_result << endl;
  25. }

運行結果: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. template<bool b, class X, class Y>
  10. struct if_
  11. {
  12. typedef X type; // use X if b is true
  13. };
  14. template<class X, class Y>
  15. struct if_<false, X, Y>
  16. {
  17. typedef Y type; // use Y if b is false
  18. };
  19. int main()
  20. {
  21. cout << "Type Size = " << sizeof(if_<sizeof(T_Left) < 4, T_Left, T_Right>::type) << endl;
  22. }
其實也是根據編譯期能確定的值,來進行編譯期的選擇。

模板元編程的應用包括:Blitz++庫;boost::mpl庫;以及《Modern C++ Design》一書中提到的typelist。

Copyright © Linux教程網 All Rights Reserved