SumType extraction

Lance Bachmeier no at spam.net
Sat Jul 6 22:15:07 UTC 2024


On Thursday, 27 June 2024 at 18:51:19 UTC, Josh Holtrop wrote:
> Hello all. In my application I came across a desire to store an 
> ordered array of handles that could point to one of several 
> different objects, and it seems like the tool I want for that 
> is SumType.
>
> I started with something like (simplified of course):
>
> ```d
> class Foo {}
> class Bar {}
>
> alias Item = SumType!(Foo, Bar);
> ```
>
> And then I could do:
>
> ```d
> Item[] items;
> items ~= Item(new Foo());
> ```
>
> But, I found I wanted while iterating through my items to 
> sometimes only operate on those of a certain type. Rather than 
> having to call SumType.match! and specify patterns to test if 
> they had the type I wanted, I wanted a more concise syntax, and 
> also the ability to just directly extract the handle, or null 
> if the item kind wasn't what I was asking for.

Have you considered 
[std.Variant](https://dlang.org/phobos/std_variant.html)? I've 
found that to be the more convenient choice if I know the type of 
an item. Something like this (untested code):

```
import std.variant;
Variant[] items;
items ~= Variant(new Foo());
// If I know items[0] is a Foo
Foo foo = *(items[0].peek!Foo);
// If I want to check that it's actually Foo
auto foo = items[0].peek!Foo;
if (foo !is null) {
   // Do something with *foo
}
```


More information about the Digitalmars-d-learn mailing list