Michał Górny
Michał Górny

Reputation: 19253

'Static' template class in a template class — encapsulation, inheritance or …?

I have a 'static' template class alike the following:

#include <cstddef>

template <size_t elem_size>
struct StaticClass
{
    static void* priv;
};

So, the class contains only static members. As the static template implies, there should be one priv variable for each elem_size.

I also have the main template class which is already inherited from another class:

template <class T>
class MainBase
{
    // types, methods...
};

template <class T>
class MainDerived : public MainBase<T>
{
    // members, methods...
};

Now, I'd like MainDerived to be able to access StaticClass<sizeof(T)>; with the implication that different types T of the same size will access the same variable. What is the most optimal method of doing so? I'm mostly thinking about memory footprint.

AFAICS, having a non-static StaticClass<sizeof(T)> member in MainDerived increases the class size by 1 (for the size of 'static' class is 1).

So I'm thinking of either of three methods:

  1. Inheriting from the StaticClass (it's a multiple inheritance then),
  2. Defining a static member of StaticClass type,
  3. Accessing StaticClass<sizeof(T)> in the methods directly.

All three methods will result in a similar source code (needing explicit specification of the class one way or another), and they all won't affect sizeof(MainDerived<T>). I'm wondering if any of them has additional implications I should be aware of.

Upvotes: 1

Views: 229

Answers (1)

Bo Persson
Bo Persson

Reputation: 92291

I see a similarity with the standard library's string class, which (in effect) has a typedef for a helper class with all static members, like

typedef std::char_traits<T>   traits_type;

and then uses traits_type::copy, traits_type::assign, etc, all through the rest of the code.

You could do something similar with your StaticClass.

typedef StaticClass<sizeof(T)>   sc;

and then use sc::priv to access to correct pointer for each class.

Upvotes: 2

Related Questions