SumType extraction

Christian Köstlin christian.koestlin at gmail.com
Sat Jul 6 18:50:04 UTC 2024


On Thursday, 27 June 2024 at 18:51:19 UTC, Josh Holtrop wrote:
> Questions:
> 4. Any other general improvements to my solution?


I know it's kind of an unpopular choice these days but one could 
go
with inheritance and polymorphism or instanceof tests. something
along the lines of
```d
import std.stdio : writeln;

class Item
{
     public void operationA()
     {
     }

     public void operationB()
     {
     }
}

class ItemA : Item
{
     override public void operationA()
     {
         writeln("ItemA");
     }
}

class ItemB : Item
{
     override public void operationB()
     {
         writeln("ItemB");
     }
}

void main(string[] args)
{
     auto items = [new ItemA(), new ItemB()];
     writeln("operation a:");
     foreach (item; items)
     {
         item.operationA();
     }
     writeln("operation b:");
     foreach (item; items)
     {
         item.operationB();
     }

     writeln("instance of:");
     foreach (item; items)
     {
         if (auto itemB = cast(ItemB) item)
         {
             writeln("Found an ItemB");
         }
     }
}
```

drawback might be, that if you add a new subtype the compiler will
not warn you that you did not implement one case for one of the
implementations.

Kind regards,
Christian


More information about the Digitalmars-d-learn mailing list