模板元编程的"hello,world"可以被认为是阶乘代码:
template <unsigned int n>
struct factorial {
enum { value = n * factorial<n - 1>::value };
};
template <>
struct factorial<0> {
enum { value = 1 };
};
Run Code Online (Sandbox Code Playgroud)
所以我们可以通过这样做得到阶乘
cout << factorial<4>::value << endl; //It will print 24
Run Code Online (Sandbox Code Playgroud)
但如果我这样做:
int N = 4;
cout << factorial<N>::value << endl; //COMPILE ERROR
Run Code Online (Sandbox Code Playgroud)
有没有办法在C++中为模板化函数提供动态值?