Merge 2 structs together (into a single struct)?
ag0aep6g
anonymous at example.com
Fri Sep 17 00:36:42 UTC 2021
On 16.09.21 22:53, jfondren wrote:
> 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;
> }
As a rule of thumb, don't use `stringof` for string mixins. There's
usually a better way.
In this case, if you make `joinstruct` a struct template, you can use
the types and init values of the fields directly, without converting
them to strings and back. Only the names need to be mixed in as strings.
----
struct JoinStruct(Structs ...)
{
static foreach (S; Structs)
{
static foreach (i, alias f; S.tupleof)
{
mixin("typeof(f) ", __traits(identifier, f),
" = S.init.tupleof[i];");
}
}
}
----
More information about the Digitalmars-d-learn
mailing list