编译模板时无限循环

时间:2014-09-04 10:20:40

标签: c++ templates generic-programming

为什么这个课程编译器会进入无限循环。我正在使用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>的情况下编写value的专精:

template <>
struct next_prime<100>
{

};

我会看到编译错误。那么,为什么甚至试图编译呢?

1 个答案:

答案 0 :(得分:2)

因为它会评估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>::valuefalse时实例化。

您可以使用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
{};