gpt4 book ai didi

c++ - 编译时间递归和条件

转载 作者:可可西里 更新时间:2023-11-01 16:27:29 25 4
gpt4 key购买 nike

我正在阅读对 "Printing 1 to 1000 without loop or conditionals" 的回复,我想知道为什么有必要在顶部答案中包含 NumberGeneration<1> 的特殊情况。

如果我删除它并在模板中添加对 N == 1 的检查(下面的代码),代码会因“模板实例化深度超过最大值”而无法编译,但我不确定为什么。条件语句在编译时的处理方式是否不同?

#include <iostream>

template<int N>
struct NumberGeneration
{
static void out(std::ostream& os)
{
if (N == 1)
{
os << 1 << std::endl;
}
else
{
NumberGeneration<N-1>::out(os);
os << N << std::endl;
}
}
};

int main()
{
NumberGeneration<1000>::out(std::cout);
}

最佳答案

代码生成和编译不会根据条件分支!考虑一下:

// don't declare bar()!

void foo()
{
if (false) { bar(); }
}

如果你从不声明bar() ,这是一个编译错误,即使永远无法到达内部范围。出于同样的原因,NumberGeneration<N-1>总是被实例化,不管那个分支是否可以到达,并且你有无限递归。

事实上,条件语句的静态类比正是模板特化:

template <> struct NumberGeneration<0> { /* no more recursion here */ };

关于c++ - 编译时间递归和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8759872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com