4

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?

iBug
  • 35,554
  • 7
  • 89
  • 134

1 Answers1

3

Specialize the class template itself:

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

template <>
class NumberGenerator<1> {
    public:
    NumberGenerator();
};
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Will I be able to use other functions from the unspecialized class in `NG<1>`? I.e. does `void NG::foo()` cover `NG<1>`? – iBug Sep 18 '17 at 12:55
  • Erm. Hope this helps? http://coliru.stacked-crooked.com/a/dabc1b56b56e3848 – sehe Sep 18 '17 at 12:58
  • No you will not be able to use the other functions. To stop the chain, you MUST remove the base-class. There's no way around that other than 1. template meta programming (good luck) 2. specializing the class template – sehe Sep 18 '17 at 12:59
  • 3
    @ibug No, not unless you use multiple inheritance, and place all common methods in the base class. – Ext3h Sep 18 '17 at 13:00
  • That's another option, depending on the situation. – sehe Sep 18 '17 at 13:01