Merge 2 structs together (into a single struct)?

jfondren julian.fondren at gmail.com
Thu Sep 16 20:53:20 UTC 2021


On Thursday, 16 September 2021 at 20:12:03 UTC, james.p.leblanc 
wrote:
> Is there some obvious, and simple solution to this
> conundrum of mine?

I would consider AAs.

```d
struct A {
     int alpha;
     float x = 1.23;
}

struct B {
     int beta;
     float y = 4.4;
     string s = "this is fine.";
}

string joinstruct(A, B)(string name) {
     string s = "struct " ~ name ~ " {";
     alias memA = __traits(allMembers, A);
     alias memB = __traits(allMembers, B);
     alias initA = A.init.tupleof;
     alias initB = B.init.tupleof;
     static foreach (i; 0 .. memA.length) {
         s ~= typeof(__traits(getMember, A, memA[i])).stringof;
         s ~= " ";
         s ~= memA[i];
         s ~= " = ";
         s ~= initA[i].stringof;
         s ~= ";\n";
     }
     static foreach (i; 0 .. memB.length) {
         s ~= typeof(__traits(getMember, B, memB[i])).stringof;
         s ~= " ";
         s ~= memB[i];
         s ~= " = ";
         s ~= initB[i].stringof;
         s ~= ";\n";
     }
     s ~= "}";
     return s;
}

unittest {
     mixin(joinstruct!(A, B)("C"));
     import std.stdio;
     writeln(C());
}
```


More information about the Digitalmars-d-learn mailing list