0

我发现了有趣的问题,并决定详细检查最佳答案。
我问自己为什么需要结构并尝试在没有结构的情况下重写代码:

#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);
}

然后我尝试重构代码。我得到了这样的东西:

#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>();
}

我不明白为什么这段代码不起作用。
有任何想法吗?

4

2 回答 2

5

The problem is that the if condition is evaluated at run-time. When you get to the instantiation where N = 1, it doesn't know that the first block of the if statement won't execute. It proceeds to instantiate out<0> and so on. If we had a static if, this would be possible, but it probably won't happen very soon.

于 2013-04-18T14:09:22.037 回答
3

Templates are expanded during compilation while if statements are only checked during run-time which is a different later stage. In your case the compiler will try to expand indefinetely as there is no specific implementation of the function for a fixed value of N(that used to be 1).

于 2013-04-18T14:09:13.500 回答