编译模板时的无限循环
Infinite loop while compiling template
为什么这门课程编译器要去无限循环。我正在使用Visual Studio 2012(编译器VC++11(。
template <unsigned N, unsigned To = N - 1>
struct is_prime
{
static const bool value = (N % To != 0) && is_prime<N, To - 1>::value;
};
template <unsigned N>
struct is_prime<N, 1>
{
static const bool value = true;
};
template <unsigned N>
struct is_prime<N, 0>
{
static const bool value = false;
};
template <unsigned N>
struct next_prime
{
private:
static const unsigned n_plus_one = N + 1;
public:
static const unsigned value = is_prime<n_plus_one>::value ? n_plus_one : next_prime<n_plus_one>::value;
};
int main()
{
cout << is_prime<5>::value << endl; //Compiles. true.
cout << is_prime<4>::value << endl; //Compiles. false.
cout << next_prime<4>::value << endl; //Infinite compiler loop.
return 0;
}
如果我写没有成员value
的next_prime<100>
专业化:
template <>
struct next_prime<100>
{
};
我会看到编译器错误。那么,为什么还要尝试编译呢?
因为它计算next_prime<4>::value
:
template <unsigned N>
struct next_prime {
// ...
static const unsigned n_plus_one = N + 1;
// ...
static const unsigned value = is_prime<n_plus_one>::value ? n_plus_one : next_prime<n_plus_one>::value;
在上述next_prime<n_plus_one>::value
中,只有在is_prime<n_plus_one>::value
false
时才能实例化。
您可以使用返回其中一种类型的std::conditional<>
修复它,具体取决于条件:
template <unsigned N>
struct next_prime : std::conditional<
is_prime<N + 1>::value
, std::integral_constant<unsigned, N + 1> // not instantiated here
, next_prime<N + 1> // not instantiated here
>::type // instantiated here
{};
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 用于循环编译的 constexpr
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 连接线程时的无限循环
- 为什么这种方法会进入无限循环?
- 由于QTextStream的无限循环
- 递归应用 C++20 范围适配器会导致编译时无限循环
- 编译模板时的无限循环