std.sumtype?

Paul Backus snarwin at gmail.com
Tue Mar 23 19:02:57 UTC 2021


On Tuesday, 23 March 2021 at 16:29:52 UTC, Steven Schveighoffer 
wrote:
>
> Consider an assert that validates a SumType is a certain type:
>
> SumType!(string, float, int) someType;
> ...
> someType.match!((T t) {assert(is(T == int)); });
>
> vs.
>
> assert(someType.typeIndex == 2);

Well, first, we would never write a naked magic number like this 
in production code, so for the sake of a fair comparison, let's 
fix that issue:

     assert(someType.typeIndex == staticIndexOf!(int, 
someType.Types));

Moving on--if I were doing this often enough for it to matter, I 
would define a helper function:

     bool contains(T, ST)(ST st)
     if (isSumType!ST)
     {
         return st.match!(value => is(typeof(value) == T));
     }

Usage:

     assert(someType.contains!int);

Personally I think this is far preferable to the typeIndex 
version in terms of readability. In terms of performance: I 
checked the generated assembly, and `ldc -O` inlines everything, 
but `dmd -O -inline` does not, so if you are using DMD you're 
leaving performance on the table here (but isn't that true in 
general?). There is also some additional compile-time overhead 
from instantiating the templates.


More information about the Digitalmars-d mailing list