对于计算阶乘,我可以使用:
template<int N> struct factorial { enum { value = N * factorial<N-1>::value }; };
template<> struct factorial<1> { enum { value = 1 }; }; //base Case然后可以使用它,如下所示
x=factorial<8>::value;
那么,是否有可能获得类似的递归模板
unsigned Log2(unsigned n, unsigned p = 0) {
return (n <= 1) ? p : Log2(n / 2, p + 1);
}我可以这样想:
template<int N,unsigned int P=0> struct Log2
{ enum { value = Log2<N/2,P+1>::value }; };但不知道如何设置一个基本的案子。
template<> struct Log2<0,???> { enum { value = ???? }; };有什么想法吗?
发布于 2013-08-14 13:11:09
可以使用部分专门化。
template <unsigned p>
struct Log2<0, p> { enum { value = p }; };
template <unsigned p>
struct Log2<1, p> { enum { value = p }; };在C++11中,您可以将函数改为constexpr,而不是创建模板。
constexpr unsigned Log2(unsigned n, unsigned p = 0) {
return (n <= 1) ? p : Log2(n / 2, p + 1);
}
std::array<int, Log2(256)> x {{1, 2, 3, 4, 5, 6, 7, 8}};
// ^^^^^^^^^ Just a compile-time function call.https://stackoverflow.com/questions/18232647
复制相似问题