Template class inheritance from a different specialization

c++, inheritance, specialization, templates

Solution

This is a standard technique that is quite often used when defining a `template` recursively.

An example of such a technique would be sequences of integers:

template<int...s> struct seq {typedef seq<s...> type;};

In particular, in their generation:

template<int max, int... s> struct make_seq:make_seq<max-1, max-1, s...> {};
template<int... s> struct make_seq<0, s...>:seq<s...> {};

which is described recursively and simply by inheriting from a different instantiation of the `template`.

To be explicit, `make_seq<7>::type` is `seq<0,1,2,3,4,5,6>` via 7 levels of recursive inheritance.

Problem

This is a question out of curiosity on C++ rules without any real practical usage. When toying around with templates, I created a class hierarchy like so: ``` #include <stdio.h> // Declaration template <int X = 0> struct A; // Specialization for X = 0 template <> struct A<0> { virtual void foo() { printf("A<0>::foo()\n"); } }; // Extended generalized implementation template <int X> struct A : public A<0> { virtual void foo() { printf("A<1>::foo()\n"); } virtual void bar() { printf("A<1>::bar()\n"); } }; int main() { A<> a0; A<1> a1; a0.foo(); a1.foo(); a1.bar(); return 0; } ``` This code compiled fine on Visual Studio and produces the expected output: ``` A<0>::foo() A<1>::foo() A<1>::bar() ``` Is this a valid C++ design practice? It certainly looks strange to me, so I'm wondering if this is some sort of undefined behaviour which just happens to work depending on compiler with lots of pitfalls and gotchas, or if it is a well-defined usage of templates. It would be interesting to see any practical examples of this.

Original source