Reputation: 19253
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:
StaticClass
(it's a multiple inheritance then),StaticClass
type,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
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