Specialize a template class?

102 views Asked by At

I am attempting to write a program that outputs 1 to 1000 without a loop or recursive function call, 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, I can't stop the chain call (NumberGenerator<1> still attempts to call NumberGenerator<0> and infinitely underflowing). How can I make the chain stop at 1?

1

There are 1 answers

5
sehe On BEST ANSWER

Specialize the class template itself:

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

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