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

344 views Asked by At

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.

3

There are 3 answers

0
JeJo On BEST ANSWER

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

2
Friedrich On

In your example, you could rewrite your code to read:

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

struct X
{
    Y z;
    int c = 0;
};

Now it is the same struct.

0
463035818_is_not_an_ai On

The two are not of same type. Maybe you actually want them to be the same type, then the "simple" way to be able to write y = x.z; is this:

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


int main() {
    X x{ 1,2,3 };
    auto y = x.z;
}

or

decltype(x.z) y;
y = x.z;