3

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 illegal (placed after the above):

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

I don't see why B<2, Rest...> is an incomplete type, as the error message states. 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*/}
};

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

prestokeys
  • 4,817
  • 3
  • 20
  • 43
  • 2
    The first is an explicit specialization (which is OK); the second would be a partial specialization (which isn't). – T.C. May 31 '15 at 20:10

1 Answers1

0

What you are trying to achieve is called partial template specialization, and is allowed only for classes, not for functions. See for example Why function template cannot be partially specialized?

Community
  • 1
  • 1
marom
  • 5,064
  • 10
  • 14
  • I knew that rule, but I thought the partial specialization here was more to do with the class than the function. After all, the error message was pointing at `B<2, Rest...>` being an incomplete type. So there is no satisfying workaround, is there? – prestokeys May 31 '15 at 20:13
  • 1
    That link isn't relevant to this question - OP isn't trying to partially specialize a function template. – Barry May 31 '15 at 21:23
  • But people are voting that I am. I also thought I wasn't trying to partially specialize a function template before posting my question. – prestokeys May 31 '15 at 21:29