标题:C++模板编译期求值
只看楼主
xyath
Rank: 1
来 自:苏州昆山
等 级:新手上路
帖 子:4
专家分:0
注 册:2009-11-7
结帖率:0
 问题点数:0 回复次数:0 
C++模板编译期求值
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
    }
搜索更多相关主题的帖子: 期求 编译 模板 
2009-11-07 14:57



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-291387-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.437510 second(s), 7 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved