注册 登录
编程论坛 C++教室

C++模板编译期求值

xyath 发布于 2009-11-07 14:57, 457 次点击
C++模板编译期求值
帖子由 tiger » 2009-08-14 20:28
下面是一段用模板求阶乘的代码,有兴趣的朋友可以把其他模板编译期求值的代码贴上来,分享一下。
代码: 全选
    /*
    * factorial.cpp
    *
    *  Created on: 2009-8-14
    *      Author: kwarph
    *        Mail: kwarph@
    */
    #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
    }
0 回复
1