use*_*012 -1 c++ templates metaprogramming template-meta-programming
模板元编程的"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++中为模板化函数提供动态值?
das*_*ght 10
不,你做不到.模板元编程的重点是在编译时进行一些计算.您的factorial示例的整个递归扩展链由编译器完成,因此它必须知道值n才能完成计算.
如果您不知道n运行时的值,则应用"常规"编程样式,因此调用factorial<N>::value变得不必要.