小编use*_*012的帖子

有没有办法在C++中为模板化函数赋予动态值?

模板元编程的"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++中为模板化函数提供动态值?

c++ templates metaprogramming template-meta-programming

-1
推荐指数
1
解决办法
177
查看次数