Zad*_*sta 2 c++ templates template-specialization
我用C++键入这段代码:
#include <iostream>
template <int n, int i = 0>
class show {
public:
show () {
if (i % 2) {
std::cout << i << std::endl;
show <n-1, i+1>();
}else {
show <n,i+1>();
}
}
};
template <int i>
class show <0, i> {};
int main()
{
show <6>();
}
Run Code Online (Sandbox Code Playgroud)
我认为它会写出6个不可分割的第一个数字2.相反,我得到一个错误
致命错误:模板实例超过最大值100
如果它应该最多实例化12个实例,为什么会出现此错误?
试试吧
show () {
if ( i % 2 )
std::cout << i << std::endl;
show<n-(i%2 ? 1 : 0), i+1>();
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你可以使用C++ 17,也可以使用
show () {
if constexpr (i % 2) {
std::cout << i << std::endl;
show <n-1, i+1>();
}else {
show <n,i+1>();
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码存在问题
show () {
if (i % 2) {
std::cout << i << std::endl;
show <n-1, i+1>();
}else {
show <n,i+1>();
}
}
Run Code Online (Sandbox Code Playgroud)
如果i % 2是真或假,这是不重要的:shows,show<n-1, i+1>和show<n, i+1>,都是实现的.因此实现了许多不必要的shows并且达到了模板实例化的最大数量.
C++ 17 if constexpr正好引入以避免这类问题.
预C++ 17,你可以解决
show<n-(i%2 ? 1 : 0), i+1>();
Run Code Online (Sandbox Code Playgroud)