Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a base class in c++ template specialization

Tags:

c++

templates

In the dusty corners of a code base I work on, I've come across a class hierarchy that looks like this:

class Base1
{
  int base1;
};

class Base2
{
  int base2;
};
template <typename T> class A : public Base1
{
      T _specialT;
};
template <> class A<int> : public Base2
{
      int _special;
};

The use of Base2 in the specialization of A is something that surprised me. I've been searching around to understand exactly what it means, haven't been able to find any examples or discussions of this sort of design.

It seems to me that what this does is cause A to inherit from both Base1 and Base2 while other uses of A that are not specialized will inherit from only Base1. That leaves me with a couple of questions:

  1. Do I understand this correctly?
  2. Are there any non-obvious caveats in added to the hierarchy this way? Why would you do this?
  3. Are there times when this would be considered good design?
like image 808
MattG Avatar asked Feb 16 '23 13:02

MattG


2 Answers

  1. No. The primary class template inherits from Base1 and only the <int> specialization inherits from Base2 (and from Base2 only).

Not knowing the context where this is used, I can't answer 2. or 3.

You can often see specializations deriving from different types in template meta-programming. For example:

template<typename T, typename U>
struct is_same : std::false_type {};

template<typename T>
struct is_same<T,T> : std::true_type {};

It's perfectly valid thing to do. Whether it is a good thing to do depends entirely on the problem being solved.

like image 155
jrok Avatar answered Feb 28 '23 01:02

jrok


A specialization of a template is completely independent, code-wise, from the normal case. So A<int> will not derive from both Base1 and Base2, just from Base2.

There are certainly cases where specializations are good design. Whether this is one is not possible to tell from your abstracted example, of course.

like image 28
Sebastian Redl Avatar answered Feb 28 '23 01:02

Sebastian Redl