Home > Blockchain >  Use a nested struct members directly
Use a nested struct members directly

Time:12-29

So I'm trying to nest a struct into another one by value, but I want to be able to import the members of the nested structs as if they are direct members of Generic struct. There seems to be a using keywork in C , but it doesn't work as I would have expected.

For example:

struct A
{
    int a;
    // some specific A stuff
};
struct B
{
    float a;
    // some specific B stuff
};

template<typename T>
struct Generic
{
    Kind kind; // an enum or an integer ID that allow to figure out what type is contained
    // some generic stuff

    // how to do this?
    using T t; // Error: a class-qualified name is required

    // some more generic stuff
};

void foo()
{
    Generic<B> g;
    g.t.a = 6.7 // we can do this with regular struct field
    g.a = 5.4; // but need to be able to do this
}

This construct is made in this way to be able to create different user-extensible views into some differently-sized item buffer, where each item is a tagged union with custom contents and common header and footer.

So the main question: How to import ("use") some struct into a different one and be able to access the nested struct' fields directly?

CodePudding user response:

There is a possible way to work around the problem by using inheritance, but it needs more structures:

// The "data" structures
struct A { ... };
struct B { ... };

// Common "header" structure
struct Header { ... };

// The "generic" structure to combine the header with the data
template<typename D>
struct Data : Header, D
{
    // Empty
};

Now you can use the B data as

Data<B> data;

The header information will come first, the actual data follow. And the size will depend on the data structure.

But please note that from a design point of view, this is highly dubious. I would prefer actual composition:

struct A
{
    // Actual A data fields follow
};

struct Data_A
{
    Header header;
    A data;
};

This allows you to read the header and data separately from the buffer. It's also more explicit about the separation of the header and the data, and should make the code clearer and easier to read, understand and maintain.

  • Related