利用模板编译期计算阶乘

来源:互联网 发布:java求二叉树的节点数 编辑:程序博客网 时间:2024/06/12 08:01
//////////////////////////////////////////////////////////////////////////
// C++ templates meta programming


template<bool, typename T1, typename T2>
struct If
{
typedef T1 type;
};


template<typename T1, typename T2>
struct If<false, typename T1, typename T2>
{
typedef T2 type;
};


template<int n>
struct Factorial_exception
{
enum {Value = -1};
};


template<int n>
struct _Factorial
{
enum { Value=n*_Factorial<n-1>::Value};
};


template<>
struct _Factorial<0>
{
enum { Value=1};
};


// 最终结果
template<int n>
struct Factorial
{
enum { Value = If< n<1, Factorial_exception<n>/*小于1时阶乘为-1 */, _Factorial<n> >::type::Value };
};


使用例举:
int i = Factorial<-2>::Value; // 该语句对应编译之后的汇编代码为: mov dword ptr [i],0FFFFFFFFh


amazing?
原创粉丝点击