gpt4 book ai didi

c++ - 编译模板时无限循环

转载 作者:行者123 更新时间:2023-11-30 04:01:34 24 4
gpt4 key购买 nike

为什么这门类(class)编译器会进入死循环。我正在使用 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;
}

如果我将编写 next_prime<100> 的特化没有成员(member)value :

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
{};

关于c++ - 编译模板时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25662966/

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