Template class function specialization

This is legal in C ++:

template <int N> class A {
    void bar() {std::cout << N << '\n';}
};

template<>
void A<2>::bar() {std::cout << "Two\n";}  // This is ok.

      

Now consider this class:

template <int...> struct B;

template <int First, int... Rest>
struct B<First, Rest...> : B<Rest...> {
    static void foo() {
        std::cout << First << ' ';
        B<Rest...>::foo();  
    }
    static void bar() {/*Bunch of code*/}
    static void baz() {/*Bunch of code*/}
};

template <>
struct B<> {
    static void foo() {}
    static void bar() {}
    static void baz() {}
};

      

Then why is the following not valid (placed after above):

template <int... Rest>
void B<2, Rest...>::foo() {  // Illegal.
    std::cout << "Two ";
    B<Rest...>::foo();
}

      

I don't understand why B<2, Rest...>

is an incomplete type as stated in the error message. So apparently the only way to achieve what I want is through this?

template <int... Rest>
struct B<2, Rest...> : B<Rest...> {
    static void foo() {
        std::cout << "Two ";
        B<Rest...>::foo();  
    }
    static void bar() {/*Same bunch of code as above*/}
    static void baz() {/*Same bunch of code as above*/}
};

      

So repeating all the code in bar () and baz ()?

+3


source to share


1 answer


What you are trying to achieve is called a private specialized pattern and is only allowed for classes, not functions. See for example Why can't a function template be partially specialized?



0


source







All Articles