Inheriting a template class from another specialization

This is a question out of curiosity about C ++ rules without any real practical use. When you played with templates, I created a class hierarchy as follows:

#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 compiles fine in Visual Studio and displays the expected result:

 A<0>::foo() A<1>::foo() A<1>::bar() 

Is this a valid C ++ design practice? This, of course, looks strange to me, so I wonder if this is some kind of undefined behavior that just works depending on the compiler with lots of traps and gotchas, or if this is a well-defined use of patterns.

It would be interesting to see practical examples of this.

+4
source share
2 answers

This is a standard method that is often used in the recursive definition of template .

An example of such a technique can be a sequence 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 another instance of template .

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

+3
source

This is true for C ++. The class template A<1> is a completely different animal from another class template A<0> .

In fact, what you built here is similar to what is called a curiously repeating pattern template .

0
source

Source: https://habr.com/ru/post/1490713/


All Articles