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.
Yis not same asdecltype(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 thedecltype(X::z)type, and does the assignment toY.Now you can write
See a live demo in godbolt.org