Merge 2 structs together (into a single struct)?

james.p.leblanc james.p.leblanc at gmail.com
Fri Sep 17 05:01:36 UTC 2021


On Friday, 17 September 2021 at 00:36:42 UTC, ag0aep6g wrote:
> On 16.09.21 22:53, jfondren wrote:
>> string joinstruct(A, B)(string name) {
>
> struct JoinStruct(Structs ...)
> {
>     static foreach (S; Structs)
>     {
>         static foreach (i, alias f; S.tupleof)
>         {
>             mixin("typeof(f) ", __traits(identifier, f),
>                 " = S.init.tupleof[i];");



Ali, jfondren, ag0aep6g,

All of your responses are greatly appreciated.  I have done test 
implementations
of them all, and they work well with my intended application. 
(Also, I learned
something new from all of them).

The struct mixin template appears to be quite robust and elegant. 
  So, I include a
simple implementation for any future readers to take it for a 
"test drive".

```d

import std.stdio;
import std.traits;

template JoinStruct(Structs ...)
{
    static foreach (S; Structs)
    {
       static foreach(i, alias f; S.tupleof)
       {
          mixin("typeof(f) ", __traits(identifier, f), " = 
S.init.tupleof[i];");
       }
    }
}

void main(){

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

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

    struct C {
       int gamma = 42;
       double z = 1.2e8;
       string t = "if this was named 's', duplicate would be 
detected at compile time";
    }

    struct D {
       mixin JoinStruct!(A,B,C);
    }

    A a;
    B b;
    C c;

    writeln("\na:", a);
    writeln("\nb:", b);
    writeln("\nc:", c)
    auto d = D();
    writeln("\nd:", d);
}

```

My next steps would be to include some UDA's to ease the getopt 
building
for command line arguments.  There is a sketch from Jesse 
Phillips at

https://dev.to/jessekphillips/argument-parsing-into-structure-4p4n

For example:

```d
// Specify The Parameter Structure
struct Options
{
    @Option("threads", "t")
    @Help("Number of threads to use.")
    size_t threads;

    @Option("file")
    @Help("Input files")
    string[] files;
}
```

Again, thanks to you and many of the D community with helping to 
learn and
appreciate the capabilities of D.  It is nice to be here.

Best Regards,
James





More information about the Digitalmars-d-learn mailing list