Aliasing a placeholding buffer in base class from derived class

49 Views Asked by At

I want to create an array of struct objects that each contain a member which holds a value. However, this value might differ in its type from object to object. As the size can't vary I decided to put a placeholding buffer in the base class which I try to alias from a templated-to-type derived class. But this doesn't work:

#include <iostream>
#include <string>

struct some_struct_base
{
    std::string name_;
    char placeholder_[sizeof(std::string)];
    some_struct_base* next_;
    some_struct_base* prev_;
};

template <typename T>
struct some_struct : some_struct_base
{
    using val = static_cast<T>(some_struct_base::placeholder_);
};


int main()
{
    std::cout << sizeof(some_struct<std::string>) << std::endl;

    some_struct_base arr[10]; // <-- this is why the size needs to be fixed
    std::cout << static_cast<some_struct<std::string>>(arr[10]).val << std::endl; // <-- allow this
}

yields:

<source>:99:17: error: expected type-specifier before 'static_cast'
   99 |     using val = static_cast<T>(some_struct_base::placeholder_);
      |                 ^~~~~~~~~~~

I can halfway understand this as val defines a type and not a variable name. But I don't want to introduce new members to the derived class (like a reference member e.g.) because this needs to run on embedded systems and another 4 bytes is already asking for too much.

How can I achieve this using minimal space / no additional overhead?

0

There are 0 best solutions below