Is std.variant useful for types only known at run time?

jfondren julian.fondren at gmail.com
Wed Sep 8 10:38:09 UTC 2021


On Wednesday, 8 September 2021 at 09:55:20 UTC, Chris Piker wrote:
> Interesting.  I presume that the big win for using std.sumtype 
> over a class set is value semantics instead of reference 
> semantics?

There's a lot to say about the precise differences. One practical 
difference that I alluded to earlier is that an incomplete 
`match!` is a compile-time error, so if you later add a fifth 
kind of time encoding to your sumtype, the compiler will give you 
a laundry list of parts of your code to update to handle the new 
case.

> So out of curiosity, say each structure implemented a function 
> to provide the desired broken-down-time, would the following 
> "virtual function" style call work?
>
> ```d
> import std.sumtype;
> struct BDTime { int y, int m, int d, int h, int m, double s };
>
> struct ISO8601 { BDTime bdTime(){ ... }  }
> struct FloatEpoch { BDTime bdTime(){ ... } }
> struct DoubleEpoch { BDTime bdTime(){ ... } }
> struct LongEpoch { BDTime bdTime(){ ... }  }
> alias Time = SumType!(ISO8601, FloatEpoch, DoubleEpoch, 
> LongEpoch);
>
> void main() {
>     import std.stdio : writeln;
>     import std.format : format;
>
>     Time e = ISO8601();
>     BDTime = e.bdTime();
> }
> ```
> or would I need to use `match!` to get the right structure type 
> and then generate the internal time representation?

You'd get an error like

```
Error: no property `bdTime` for type 
`std.sumtype.SumType!(ISO8601, ...)`
```

bdTime is defined for the individual times and not for the 
sumtype. You could have a match! that pulls out each member and 
calls its individual .bdTime(), but probably a more natural 
solution is to define bdTime only once, against the sumtype, 
where it has an internal `match!` that pulls out the different 
properties of the members that are necessary for each to 
construct a BDTime.


More information about the Digitalmars-d-learn mailing list