模板元编程

    技术2022-05-20  54

    不使用乘法,for,if,else实现sigma(n)  n必须是常数,在编译期进行计算

    #include<iostream> using namespace std; template <int N> struct Factorial { static const int value=N+Factorial<N-1>.value; //enum { value = N + Factorial<N - 1>::value }; }; template <> struct Factorial<0> { static const int value=0; //enum { value = 1 }; }; int main() { cout<<Factorial<4>.value<<endl; return 0; } 

    enum的用法叫做emun hack

    http://stackoverflow.com/questions/2172647/template-metaprogramming-difference-between-using-enum-hack-and-static-const

    http://stackoverflow.com/questions/499106/what-does-template-unsigned-int-n-mean

    http://en.wikipedia.org/wiki/Template_metaprogramming


    最新回复(0)