C++模板编译期求值
帖子由 tiger » 2009-08-14 20:28
http://www.xuanyuan-soft.cn/forums下面是一段用模板求阶乘的代码,有兴趣的朋友可以把其他模板编译期求值的代码贴上来,分享一下。
代码: 全选
    /*
    * factorial.cpp
    *
    *  Created on: 2009-8-14
    *      Author: kwarph
    *        Mail: 
kwarph@gmail.com    */
    #include <iostream>
    using namespace std;
    template<unsigned n>
    struct Factorial {
        static const unsigned v = n * Factorial<n - 1>::v;  // 递归
    };
    // 模板特化,也是上面递归的终止条件
    template<>
    struct Factorial<1> {
        static const unsigned v = 1;
    };
    // 模板特化,只匹配Factorial<0>情况
    template<>
    struct Factorial<0> {
        static const unsigned v = 0;
    };
    int main() {
        cout << Factorial<5>::v << endl;    // 120
        cout << Factorial<0>::v << endl;    // 0
    }
技术者五境界:工、匠、师、艺、道