为了计算阶乘,我可以使用:
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 = ???? }; };
有任何想法吗 ?
ken*_*ytm 10
你可以使用部分专业化
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.
| 归档时间: | 
 | 
| 查看次数: | 2316 次 | 
| 最近记录: |