Real Donald Trump
Real Donald Trump

Reputation: 422

Is it possible to merge unions?

I have this struct that defines a 32-bit unsigned integer.

struct WORD
{
    union
    {
        struct
        {
            BYTE byte1; // lowest
            BYTE byte2;
            BYTE byte3;
            BYTE byte4; // highest
        };
        uint32_t raw;
    };
};

I want to create subclasses of this struct for example

struct CPSR : WORD
{
    union
    {
        struct
        {
            uint32_t mode: 5;
            uint32_t thumbState : 1;
            uint32_t fiqDisable : 1;
            uint32_t irqDisable : 1;
            uint32_t unused : 20;
            uint32_t V : 1;
            uint32_t C : 1;
            uint32_t Z : 1;
            uint32_t N : 1;
        };
        uint32_t raw;
    };
};

I want this struct to be able to access and modify fields byteX from the parent struct. The changes made to byteX must also be reflected in the child struct's internal struct. In order to do that, the union from the parent struct must be merged into this child struct. In other words, I want this child struct to behave the exact same way as

struct CPSR
{
    union
    {
        struct
        {
            uint32_t mode: 5;
            uint32_t thumbState : 1;
            uint32_t fiqDisable : 1;
            uint32_t irqDisable : 1;
            uint32_t unused : 20;
            uint32_t V : 1;
            uint32_t C : 1;
            uint32_t Z : 1;
            uint32_t N : 1;
        };

        struct
        {
            BYTE byte1; // lowest
            BYTE byte2;
            BYTE byte3;
            BYTE byte4; // highest
        };

        uint32_t raw;
    };
};

Is it possible to merge unions like this?

Godbolt: https://godbolt.org/z/7beresKaz

Upvotes: 0

Views: 107

Answers (1)

catnip
catnip

Reputation: 25388

Inheritance won't work. I think you're looking for:

struct CPSR
{
    union
    {
        struct
        {
            uint32_t mode: 5;
            uint32_t thumbState : 1;
            uint32_t fiqDisable : 1;
            uint32_t irqDisable : 1;
            uint32_t unused : 20;
            uint32_t V : 1;
            uint32_t C : 1;
            uint32_t Z : 1;
            uint32_t N : 1;
        };

        WORD w;
    };
};

Plus what @Schol-R-LEA said.

I know that's not quite the same thing, but I think it's the closest you're going to get. And you're not type-punning, I hope...

Upvotes: 1

Related Questions