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

來源:互聯網
上載者:User

    C++模板元編程,是使用template進行編譯期運算的一種機制,可以認為是C++的一種編程方式。

第一個例子:計算整數N的階乘。

//模板的一般形式template<int N>class Factorial{public:    enum    {        _result = N * Factorial<N-1>::_result    };};//用於結束遞迴規則的特化模板template<>class Factorial<0>{public:    enum    {        _result = 1    };};int main(){    const int Num = 10;    cout << Num << "! = " << Factorial<Num>::_result << endl;}

運行結果: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》一文中舉的例子。

struct T_Left{    int value;};struct T_Right{    char value;};template<bool b, class X, class Y>struct if_{    typedef X type; // use X if b is true};template<class X, class Y>struct if_<false, X, Y>{    typedef Y type; // use Y if b is false};int main(){    cout << "Type Size = " << sizeof(if_<sizeof(T_Left) < 4, T_Left, T_Right>::type) << endl;}

其實也是根據編譯期能確定的值,來進行編譯期的選擇。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.