• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            C++ Programmer's Cookbook

            {C++ 基礎(chǔ)} {C++ 高級(jí)} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            模版元編程(Template Meta Programming )

             

            I.背景

            C
            ++在很多人的心目中,一直是一種OO語言,而事實(shí)上,現(xiàn)在對(duì)C++的非OO部分的各種使用被逐漸地挖掘出來,其中最大的部分莫過于是 template。STL、loki、boost,,很多先行者為我們提供了方案,有的已經(jīng)被列入C++標(biāo)準(zhǔn)的一部分。template的一個(gè)重要使用方法就是template meta programming,它利用編譯器對(duì)于template的解釋是靜態(tài)的這一特性,讓編譯器在編譯時(shí)做計(jì)算,可以有效的提高程序的運(yùn)行速度。有關(guān)于 template meta programming的記載,最早見于Erwin Unruh,他在1994年寫了一個(gè)用template計(jì)算質(zhì)數(shù)的程序。我希望通過這篇文章介紹一些TMP的基本技巧和應(yīng)用,并且最終完成一個(gè)質(zhì)數(shù)計(jì)算程序。
            (閱讀本文的過程中,建議你試圖編譯每一個(gè)給出的程序。由于所有的類只需要public成員,所以都用struct聲明,但是仍然稱之為類。)

            II.技術(shù)

            通常我們編寫一個(gè)(?。┏绦?,需要的語言支持其實(shí)不必很多,只要有順序、選擇和循環(huán)三種控制結(jié)構(gòu)理論上就可以寫出大多數(shù)程序了。我們先用TMP建立一個(gè)簡單的語言環(huán)境。

            1.打印

            程序有了結(jié)果,需要有一個(gè)方式反饋給運(yùn)行者,這里我們利用C
            ++的出錯(cuò)信息,建立一個(gè)打印函數(shù)。要知道我們希望一切都在編譯的時(shí)候結(jié)束,那么我們就必須讓C++編譯器在編譯信息里面告訴我們,所以我們利用編譯器的出錯(cuò)信息。當(dāng)然這只是一個(gè)trick,如果你的TMP只是程序的一部分,你可以使用正常的輸入輸出。

            template
            <unsigned int value>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            這個(gè)類,每當(dāng)別人引用到它的result的時(shí)候,編譯器就會(huì)打印出錯(cuò)信息,因?yàn)橐粋€(gè)unsigned int是不能隱式的轉(zhuǎn)成一個(gè)unsigned char
            *的。譬如下面這段程序

            template
            <unsigned int value>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            unsigned 
            int test1 = print<77>::result;
            unsigned 
            int test2 = print<123>::result;

            在我的Dev C
            ++里,會(huì)輸出

            main.cpp: In instantiation of `print
            <77>':
            main.cpp:7: instantiated from here
            main.cpp:
            4: invalid conversion from `unsigned char*' to `unsigned int'
            main.cpp: In instantiation of `print<123>':
            main.cpp:8: instantiated from here
            main.cpp:
            4: invalid conversion from `unsigned char*' to `unsigned int'

            這個(gè)輸出雖然不是很好看,但也算是差強(qiáng)人意。

            2.選擇

            Andrei Alexanderescu在他的大作Modern C
            ++ Design里面使用過一個(gè)類,可以根據(jù)bool的值選擇不同的類型。今天我們要寫的一個(gè)是根據(jù)bool的值選擇不同的整數(shù)。

            template
            <bool condition, unsigned int value1, unsigned int value2>
            struct template_if
            {
            static 
            const unsigned int result = value1;
            };

            template
            <unsigned int value1, unsigned int value2>
            struct template_if
            <false, value1, value2>
            {
            static 
            const unsigned int result = value2;
            };

            這里用到了模板的特化,如果你對(duì)這個(gè)不熟悉,那么大致可以這樣理解:第一個(gè)template_if的定義告訴編譯器,“一般的” template_if,會(huì)選擇第一個(gè)值作為結(jié)果。第二個(gè)template_if告訴編譯器,如果第一個(gè)參數(shù)是false的話,我們就使用第二個(gè)值(第三個(gè)參數(shù))作為結(jié)果。下面這段代碼演示了template_if的用法。

            template
            <unsigned int value>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <bool condition, unsigned int value1, unsigned int value2>
            struct template_if
            {
            static 
            const unsigned int result = value1;
            };

            template
            <unsigned int value1, unsigned int value2>
            struct template_if
            <false, value1, value2>
            {
            static 
            const unsigned int result = value2;
            };

            template
            <unsigned int value>
            struct print_if_77
            {
            static 
            const unsigned int result = template_if<value == 77 , print<value>::result , 0>::result;
            };

            unsigned 
            int test1 = print_if_77<77>::result;
            unsigned 
            int test2 = print_if_77<123>::result;

            如果你去編譯這段代碼的話,你會(huì)發(fā)覺77和123都被打印出來了,雖然錯(cuò)誤信息不一樣,但是這不是我們想要的結(jié)果。為什么呢?很遺憾,對(duì)C
            ++編譯器來說,template_if<true1100>和template<true1200>是兩個(gè)不同的類,雖然后一個(gè)參數(shù)的值我們并不關(guān)心,但是編譯器必須在template初始化的時(shí)候,給出所有的參數(shù),這就導(dǎo)致它會(huì)去計(jì)算 print<value>::result,當(dāng)然,計(jì)算的結(jié)果就是報(bào)錯(cuò)。也就是說,因?yàn)榫幾g器要計(jì)算這個(gè)值才導(dǎo)致了我們的print不可用,要解決這個(gè)問題,有兩個(gè)方法:或者讓編譯器不計(jì)算這個(gè)值,或者讓編譯器在某些情況下可以計(jì)算出正確的值。

            方法一可以讓編譯器不計(jì)算這個(gè)值,通過修改template_if,我們傳入兩個(gè)不同的類,而不是unsigned 
            int。
            首先修改print,加一個(gè)新的類dummy_print:

            template
            <unsigned int value>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int value>
            struct dummy_print
            {
            static 
            const unsigned int result = value;
            };

            接著,加入一套對(duì)類型進(jìn)行選擇的模板:

            template
            <bool condition, typename T1, typename T2>
            struct template_if_type
            {
            static 
            const unsigned int result = T1::result;
            };

            template
            <typename T1, typename T2>
            struct template_if_type
            <false, T1, T2>
            {
            static 
            const unsigned int result = T2::result;
            };

            這樣原先的程序就變成:

            template
            <unsigned int value>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int value>
            struct dummy_print
            {
            static 
            const unsigned int result = value;
            };

            template
            <bool condition, typename T1, typename T2>
            struct template_if_type
            {
            static 
            const unsigned int result = T1::result;
            };

            template
            <typename T1, typename T2>
            struct template_if_type
            <false, T1, T2>
            {
            static 
            const unsigned int result = T2::result;
            };

            template
            <unsigned int value>
            struct print_if_77
            {
            static 
            const unsigned int result = template_if_type<value == 77 ,
             dummy_print
            <value> , print<value>>::result;
            };

            void main()
            {
            unsigned 
            int test1 = print_if_77<77>::result;
            //unsigned int test2 = print_if_77<123>::result;
            }

            現(xiàn)在的“運(yùn)行結(jié)果”非常正確。

            方法二可以讓編譯器在某些情況下計(jì)算出正確的值,我們加一套新的模板:

            template
            <bool condition, unsigned int value>
            struct print_if
            {
            static 
            const unsigned int result = value;
            };

            template
            <unsigned int value>
            struct print_if
            <false, value>
            {
            static 
            const unsigned int result = (unsigned char*)value;

            };

            原先的程序變?yōu)椋?br>template
            <bool condition, unsigned int value>
            struct print_if
            {
            static 
            const unsigned int result = value;

            };

            template
            <unsigned int value>
            struct print_if
            <false, value>
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int value>
            struct print_if_77
            {
            static 
            const unsigned int result = print_if<value == 77 , value>::result;
            };

            void main()
            {
            unsigned 
            int test1 = print_if_77<77>::result;
            //unsigned int test2 = print_if_77<123>::result;
            }


            輸出也是正確的。

            這兩種方案,我個(gè)人傾向于后者,因?yàn)槠鋵?shí)我們一定是要做一次判斷的,并且這次判斷一定會(huì)添加新的類,那么還是print_if的解決方案比較直觀。

            3. 循環(huán)

            首先必須明確的是,template不可能實(shí)現(xiàn)我們一般意義上的循環(huán),但是它可以做一件和循環(huán)類似的事情:迭代。
            如果有這樣一個(gè)循環(huán):
            for( unsigned int i = 0 ; i < value ; ++i )
            我們可以這樣寫:

            template
            <unsigned int value>
            struct 
            loop
            {
            static 
            const unsigned int result = loop<value - 1>::result + 1;
            };

            template
            <>
            struct 
            loop<0>
            {
            static 
            const unsigned int result = 0;
            };

            這就是告訴編譯器,我們的迭代從0開始,到value結(jié)束,每個(gè)值是前者加1。
            下面給出一個(gè)更廣泛的循環(huán)的實(shí)現(xiàn):
            for( unsigned int i = begin ; i < end ; i = i + step ),假設(shè)0<=begin<end,并且step>0。(更復(fù)雜的情況,總可以通過template specialization分派完成)

            template
            <unsigned int begin, unsigned int end, unsigned int step, bool loop_continue = begin < end >
            struct 
            loop
            {
            static 
            const unsigned int result = loop< begin + step, end, step>::result - step;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step>
            struct 
            loop<begin, end, step, false>
            {
            static 
            const unsigned int result = begin;
            };

            這里的result的計(jì)算過程不重要,關(guān)鍵是為了驅(qū)動(dòng)編譯器進(jìn)一步的實(shí)例化模板。
            下面是一個(gè)實(shí)例程序,用來打印13到29之間的整數(shù),步長為5。

            template
            <bool condition, unsigned int value>
            struct print_if
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int value>
            struct print_if
            <false, value>
            {
            static 
            const unsigned int result = value;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step, bool loop_continue = begin < end >
            struct 
            loop
            {
            static 
            const unsigned int result = loop< begin + step, end, step>::result - step;
            static 
            const unsigned int print_result = print_if<true, result>::result;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step>
            struct 
            loop<begin, end, step, false>
            {
            static 
            const unsigned int result = begin;
            };

            static unsigned 
            int result = loop<13,29,5>::result;

            III.應(yīng)用

            上面我已經(jīng)介紹了怎樣用TMP實(shí)現(xiàn)打印,選擇和循環(huán)了,現(xiàn)在我們來把這些投入運(yùn)用。下面我會(huì)用上面的所提供的機(jī)制,寫兩個(gè)程序:計(jì)算階乘和計(jì)算質(zhì)數(shù)。

            1.計(jì)算階乘

            我們先寫一個(gè)普通的C
            ++程序來計(jì)算階乘:

            #include 
            <iostream>

            int main()
            {
            unsigned 
            int limit = 10;
            unsigned 
            int factorial = 1;
            for( unsigned int i = 1 ; i <= limit ; ++ i )
            factorial 
            *= i;
            std::cout
            <<factorial<<std::endl;
            }

            這個(gè)程序是一個(gè)一重循環(huán),我們就用循環(huán)來做:

            template
            <unsigned int value>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step, bool loop_continue = begin < end >
            struct 
            loop
            {
            static 
            const unsigned int result = loop< begin + step, end, step>::result * begin;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step>
            struct 
            loop<begin, end, step, false>
            {
            static 
            const unsigned int result = begin;
            };

            static unsigned 
            int result = print<loop<1101>::result>::result;

            因?yàn)檫@里不必要盤算是否輸出,所以就直接用print了。

            2.計(jì)算質(zhì)數(shù)

            同樣,我們先寫一個(gè)普通的程序來計(jì)算:

            #include 
            <iostream>

            int main()
            {
            unsigned 
            int limit = 30;
            for( unsigned int i = 2 ; i <= limit ; ++i )
            {
            unsigned 
            int j;
            for( j = 2 ; j < i ; ++j )
            if( i % j == 0 )
            break;
            if( i == j )
            std::cout
            <<i<<std::endl;
            }
            }

            這里用到了兩層循環(huán),而且還是用了分支和打印。用我們提供的機(jī)制轉(zhuǎn)化成TMP形式如下:

            template
            <bool condition, unsigned int value>
            struct print_if
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int value>
            struct print_if
            <false, value>
            {
            static 
            const unsigned int result = value;
            };

            template
            <bool condition, unsigned int value1, unsigned int value2>
            struct template_if
            {
            static 
            const unsigned int result = value1;
            };

            template
            <unsigned int value1, unsigned int value2>
            struct template_if
            <false, value1, value2>
            {
            static 
            const unsigned int result = value2;
            };

            // 這里增加一個(gè)i作為參數(shù),因?yàn)樵趦?nèi)循環(huán)也需要知道外部的i的值

            template
            <unsigned int i, unsigned int begin, unsigned int end, unsigned int step, bool loop_continue = begin < end >
            struct inner_loop
            {
            static 
            const unsigned int result = template_if<i % begin,
            inner_loop
            < i, begin + step, end, step>::result,
            begin
            >::result;
            };

            template
            <unsigned int i, unsigned int begin, unsigned int end, unsigned int step>
            struct inner_loop
            <i, begin, end, step, false>
            {
            static 
            const unsigned int result = begin;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step, bool loop_continue = begin < end >
            struct outer_loop
            {
            static 
            const unsigned int result = outer_loop< begin + step, end, step>::result;
            static 
            const unsigned int is_prime = inner_loop<begin, 2, begin, 1>::result == begin;
            static 
            const unsigned int print_result = print_if<is_prime, begin>::result;
            };

            template
            <unsigned int begin, unsigned int end, unsigned int step>
            struct outer_loop
            <begin, end, step, false>
            {
            static 
            const unsigned int result = 0;
            };

            static unsigned 
            int result = outer_loop<2301>::result;

            III.細(xì)節(jié)

            另外有兩點(diǎn)要說一下:
            我們的template_if其實(shí)有一種更簡單的寫法,就是?:表達(dá)式。
            而我們的print_if和print其實(shí)可以用確省的模板參數(shù)來統(tǒng)一,唯一的區(qū)別是,要把value放在condition前面。

            template
            <unsigned int value, bool condition = true>
            struct print
            {
            static 
            const unsigned int result = (unsigned char*)value;
            };

            template
            <unsigned int value>
            struct print
            <value,false>
            {
            static 
            const unsigned int result = value;
            };

            這樣你可以用print
            <value>來打印一個(gè)數(shù)值,也可以用print<value, condition>來做判斷打印。

            IIII.后記

            很久以前看Inside OLE2的時(shí)候,記得作者說過一句話:作者因?yàn)閷憰靼?。我其?shí)幾年前就寫過類似的程序,但是從來沒有對(duì)這樣程序的寫法進(jìn)行過總結(jié)以至于每一次都是在重新開始。而寫完這篇文章后,我覺得自己比過去明白很多。template meta programming還有很多不同的應(yīng)用,我以后有機(jī)會(huì)會(huì)繼續(xù)介紹給大家。
            對(duì)于這篇文章有任何問題,請發(fā)信到 polyrandom@hotmail.com 和我聯(lián)系,也請?jiān)L問 http:
            //www.allaboutprogram.com/ 以獲得最近的更新。

            posted on 2007-03-05 10:33 夢在天涯 閱讀(5190) 評(píng)論(2)  編輯 收藏 引用 所屬分類: CPlusPlus

            評(píng)論

            # re: 模版元編程(Template Meta Programming ) 2007-03-06 09:10 gql

            程序好像寫亂了吧  回復(fù)  更多評(píng)論   

            # re: 模版元編程(Template Meta Programming )[未登錄] 2007-04-30 16:50 recorder

            暈S,看得頭大,建議看榮耀在c++大會(huì)上的演講PPT《C++模板元編程技術(shù)與應(yīng)用》,那個(gè)容易理解一些。  回復(fù)  更多評(píng)論   

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評(píng)論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804314
            • 排名 - 5

            最新評(píng)論

            閱讀排行榜

            久久精品国产亚洲Aⅴ蜜臀色欲| 国产成人精品久久一区二区三区av | 久久精品麻豆日日躁夜夜躁| 久久精品国产精品国产精品污| 一本色综合久久| 热99re久久国超精品首页| 国产成人精品综合久久久久| 免费观看久久精彩视频| 一本一道久久综合狠狠老| 欧美与黑人午夜性猛交久久久 | 香蕉久久永久视频| 国内精品久久国产大陆| 国产成年无码久久久免费| 精品久久久久久久中文字幕 | 久久久久亚洲av成人无码电影 | 亚洲国产二区三区久久| 久久99精品久久久久久动态图| 婷婷久久综合九色综合绿巨人| 色噜噜狠狠先锋影音久久| 久久久免费精品re6| 亚洲综合伊人久久综合| 亚洲国产视频久久| 久久综合五月丁香久久激情| 一本久久a久久精品综合夜夜| 波多野结衣中文字幕久久| 久久精品无码午夜福利理论片| 久久人人爽人人爽人人片av麻烦 | 久久久精品2019免费观看| 国产A三级久久精品| 精品伊人久久大线蕉色首页| 一本一道久久a久久精品综合 | 97久久精品人人做人人爽| 国产∨亚洲V天堂无码久久久| 久久久久久亚洲精品成人| 色综合久久久久综合体桃花网| 一本一本久久aa综合精品| 亚洲欧美成人综合久久久| 久久久久久久久无码精品亚洲日韩 | 精品一久久香蕉国产线看播放| 国产精品日韩欧美久久综合| 国产三级精品久久|