February 06, 2006

用 C++ Template 算階層

數學的階層運算實做上有很多方式,剛剛讀 AK's weblog [Fun with C++ templates: let the compiler compute the factorial!],發現這個特別的技巧,直接使用 C++ Template 的語意來達成:
    jserv@venux:/tmp$ cat factorial.cc
    #include <iostream>
    template <int N>
        struct fact {
            enum { value = N * fact<N - 1>::value };
    };
    template <>
    struct fact<1> {
        enum { value = 1 };
    }; 
    int main()
    {      
        std::cout << "5! = " << fact<5>::value << std::endl; 
    }
    jserv@venux:/tmp$ g++ -o factorial factorial.cc
    jserv@venux:/tmp$ ./factorial
    5! = 120
真有意思!
由 jserv 發表於 February 6, 2006 11:09 AM
迴響

這算是 C++ template 的進階技巧,以下的書籍也有介紹:

* C++ Template: The Complete Guide, Chapter 17, Metaprograms

不過個人認為,除非是為了達到像 Boost 或 Loki 這種程度的 library,否則,這種技巧還是玩玩就好。

william 發表於 February 6, 2006 09:38 PM
發表迴響









記住我的資訊?