Magusviper
Magusviper

Reputation: 134

How can sizeof childclass be used in a parent template class with the child class as a template argument?

I'm reverse engineering and recreating a program which implements global static singletons. "A" would be a class that is stored in the singleton, and "B" is the singleton itself. Is there any way to make the following code work?

template <class TClass>
class B
{
    static char cBuffer[sizeof(TClass)];
};

class A : public B<A> {
  int a;
  int b;
};

This code snippet generates the following error:

<source>:4:22: error: invalid application of 'sizeof' to an incomplete type 'A'
        static char cBuffer[sizeof(TClass)];
                            ^~~~~~~~~~~~~~
<source>:7:18: note: in instantiation of template class 'B<A>' requested here
class A : public B<A> {
                 ^
<source>:7:7: note: definition of 'A' is not complete until the closing '}'
class A : public B<A> {
      ^

Upvotes: 4

Views: 90

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36483

You could do this but it's less than ideal:

template <class TClass>
class B
{
    static char cBuffer[];
};

class A : public B<A> {
  int a;
  int b;
};

template <>
char B<A>::cBuffer[sizeof(A)];

Upvotes: 3

Related Questions