template/mixin magic for to! auto inferring type from variable

Paul Backus snarwin at gmail.com
Sat Feb 3 02:20:13 UTC 2024


On Friday, 2 February 2024 at 23:25:37 UTC, Chris Katko wrote:
> The auto solution won't work for a struct however which I'm 
> using:
>
> ```D
> struct procTable{ //contains all the fields inside a file I'm 
> parsing
>    uint time;
>    int priority;
>    string name;
>    // etc
>    }
> ```

Maybe you can use `typeof` in that case?

```d
procTable pt;
pt.time = to!(typeof(pt.time))(data[1]);
// etc
```

...although I guess then you're repeating the field name, which 
isn't great either.

You could avoid the repetition by wrapping the above pattern up 
in a helper function, though:

```d
void convertAssign(Dest, Value)(ref Dest dest, Value value)
{
     import std.conv;
     dest = to!Dest(value);
}

void main()
{
     string[3] data = ["100", "-5", "foobar"];

     uint time;
     int priority;
     string name;

     time.convertAssign(data[0]);
     priority.convertAssign(data[1]);
     name.convertAssign(data[2]);

     assert(time == 100);
     assert(priority == -5);
     assert(name == "foobar");
}
```


More information about the Digitalmars-d-learn mailing list