利用模板编译期计算阶乘

2014-11-24 07:13:26 · 作者: · 浏览: 0
//////////////////////////////////////////////////////////////////////////
// C++ templates meta programming
template
struct If
{
typedef T1 type;
};
template
struct If
{
typedef T2 type;
};
template
struct Factorial_exception
{
enum {Value = -1};
};
template
struct _Factorial
{
enum { Value=n*_Factorial::Value};
};
template<>
struct _Factorial<0>
{
enum { Value=1};
};
// 最终结果
template
struct Factorial
{
enum { Value = If< n<1, Factorial_exception/*小于1时阶乘为-1 */, _Factorial >::type::Value };
};
使用例举:
int i = Factorial<-2>::Value; // 该语句对应编译之后的汇编代码为: mov dword ptr [i],0FFFFFFFFh
amazing