////////////////////////////////////////////////////////////////////////// // 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?