4

In other words: Is it possible to make a template specialisation that inherits from its base, like this:

template <class T>  
class A{};  
template <>  
class A<int>:public A<>{};  

so that A has all of A's functions? I'm new here, so I dunno how to format, just in case the code comes up incorrectly.

StAlRuth
  • 59
  • 6

1 Answers1

5

You can, with a bit of trickery. This pattern is sometimes called “template subclassing” and is used extensively in the SeqAn library.

The trick is to give the base class an additional template argument tag which determines the type identity:

template <typename T, typename Spec = void>
struct A { … };

// inheritance tag:
struct Derived { };

template <typename T>
struct A<T, Derived> : public A<T, void> { … };

Here, void denotes the base (you could also use a dedicated tag Base but void works fine) and Derived, an empty struct, denotes the derived class.

Now you can instantiate and use the templates as follows:

A<int> the_base;
A<int, Derived> the_derived;

the_base.do_something();
the_derived.do_something();

For a real-world example, consider the String class from SeqAn:

String<Dna> some_dna = "GATTACA";
String<Dna, Packed> more_dna = "GATTACA";

The second type derived from the first one, but is a specialisation which packs its characters as tightly as possible (for DNA, this means putting four DNA characters in each byte).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    @HighCommander I appreciate edits with corrections in general but next time it would be nice if you could wait a bit after the original submission in case the original author is still editing his own post (as was the case here). – Konrad Rudolph May 30 '12 at 09:28