Specialize class templates?

I'm trying to write a program that outputs 1 to 1000 without calling a loop or recursive function, and I come up with this

#include <iostream>

template <int N>
class NumberGenerator : public NumberGenerator<N-1>{
    public:
    NumberGenerator();
};

template <int N>
NumberGenerator<N>::NumberGenerator(){
    // Let it implicitly call NumberGenerator<N-1>::NumberGenerator()
    std::cout << N << std::endl;
}

template <>
NumberGenerator<1>::NumberGenerator(){
     // How do I stop the implicit call?
     std::cout << 1 << std::endl;
}

int main(){
    NumberGenerator<1000> a; // Automatically calls the constructor
    return 0;
}

The problem is that I cannot stop the chain ( NumberGenerator<1>still trying to call NumberGenerator<0>and overflowing endlessly). How to make a circuit stop at 1?

+4
source share
1 answer

Specialize the template itself:

template <int N>
class NumberGenerator : public NumberGenerator<N-1>{
    public:
    NumberGenerator();
};

template <>
class NumberGenerator<1> {
    public:
    NumberGenerator();
};
+3
source

Source: https://habr.com/ru/post/1685881/


All Articles