Hen*_*son 1 c++ recursion template-meta-programming
这是我目前的代码:
template<int n>
struct N{
static const int k = (n >= 2) ? (1 + N<n-2>::k) : N<0>::k;
};
template<>
struct N<0>{
static const int k = 0;
};
Run Code Online (Sandbox Code Playgroud)
以下编译:
int main(int, char *[])
{
cout << N<2>::k;
getchar();
}
Run Code Online (Sandbox Code Playgroud)
以下内容无法编译:
int main(int, char *[])
{
cout << N<1>::k;
getchar();
}
Run Code Online (Sandbox Code Playgroud)
编译器是否急切地计算?:运算符的正确分支?如果是这样,我怎么能懒得评价呢?
如果您打算使用模板专业化,那就是我在整个过程中使用的内容:
template<int n>
struct N{
static const int k = 1 + N<n-2>::k;
};
template<>
struct N<1>{
static const int k = 0;
};
template<>
struct N<0>{
static const int k = 0;
};
Run Code Online (Sandbox Code Playgroud)
除非你打算用模板做这件事,否则我通常会喜欢这样的事情:
int constexpr N(int n) { return n/2; }
Run Code Online (Sandbox Code Playgroud)