c++c++11structvariable-assignmentclass-members

How to assign values of structs with different name but exactly same element and type (C++11)?


I got two structs. Some parts of the two structs have exactly the same element type (and name).

How can I assign one with another's value?

as below demonstrated:

struct X
{
    struct {
        int a = 0;
        int b = 0;
    } z;
    int c = 0;
};

struct Y
{
    int a = 0;
    int b = 0;
};

int main()
{
    X x{ 1,2,3 };
    Y y;
    // I know i can do:
    y.a = x.z.a;
    y.b = x.z.b;

    // Is there a simple way like:
    // y = x.z;
}

I looked into memcpy but in my real case, the X is much more complicated and dynamic in length. memcpy looks not quite help for me.


Solution

  • Is there a simple way like: y = x.z; ?

    Y is not same as decltype(X::z). Therefore, it is not possible without any further tweaks.

    One way is, to provide copy assignment operator overload for Y, which can accept the decltype(X::z) type, and does the assignment to Y.

    struct Y
    {
        int a = 0;
        int b = 0;
    
        using Z_t = decltype(X::z);
        Y& operator=(const Z_t& z)
        {
            a = z.a;
            b = z.b;
            return *this;
        }
    };
    

    Now you can write

    X x{ 1,2,3 };
    Y y;
    
    y = x.z;
    

    See a live demo in godbolt.org