Search code examples
c++unions

Can I use a union mapping a list of member against a struct?


I'd like to access member of a union by member name or by a "wrapped" structs, such as:

#include <iostream>

struct MyClass
{   
    union {
        int t1;
        float t2;
        struct {
            int t1;
            float t2; 
        } mySharedData;
    };

    MyClass() {
    }
};

int main()
{
    MyClass myClass;

    myClass.t2 = 10.1;
    std::cout << myClass.mySharedData.t2 << std::endl;
}

but it seems that t2 and mySharedData.t2 are not pointing to the same memory. Is there a way to do somethings like this? So I can access to a sub-group of members by its name or by grouped struct.


Solution

  • It seems you just want "alias" for your members.

    union is NOT the solution.

    You might, with a little different syntax, have those alias.

    With

    struct MyClass
    {
        struct {
            int t1 = 0;
            float t2 = 0; 
        } mySharedData;
    
        MyClass() {}
    
        // const version omitted for simplicity.
    #if VERSION_1
        auto operator ->() { return &mySharedData; }
    #else
        auto& t1() { return mySharedData.t1; }
        auto& t2() { return mySharedData.t2; }
    #endif
    };
    

    You might have

    myClass->t1 = 42;     // version 1 o->t1 instead of o.t1
    myClass.t2() = 10.1f; // version 2 o.t2() instead of o.t2()
    
    std::cout << myClass.mySharedData.t2; // and regular access.
    

    Demo