evl*_*gii 0 c++ recursion templates
我找到了有趣的问题,并决定详细检查最佳答案.
我问自己为什么需要结构并尝试在没有它的情况下重写代码:
#include <iostream>
template <int N> void out(std::ostream& os) {
out<N-1>(os);
os << N << std::endl;
}
template <> void out<1>(std::ostream& os){
os << 1 << std::endl;
}
int main(){
out<100>(std::cout);
}
Run Code Online (Sandbox Code Playgroud)
然后我试着重构代码.我有这样的事情:
#include <iostream>
template <int N> void out() {
if (N != 1) {
out<N-1>();
std::cout << N << std::endl;
}
else {
std::cout << 1 << std::endl;
}
}
int main(){
out<100>();
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这段代码不起作用.
有任何想法吗?