简体   繁体   中英

Specialize a template class?

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?

Specialize the class template itself:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM