Simplify some C-style code

sfp sfp at hush.ai
Wed Dec 25 07:49:28 UTC 2024


I have some code like this:
```
enum DomainType {
   Ball,
   Box,
   CsgDiff
}

struct Domain(int Dim) {
   DomainType type;
   union {
     Ball!Dim ball;
     Box!Dim box;
     CsgDiff!Dim csgDiff;
   }

   this(Ball!Dim ball) {
     this.type = DomainType.Ball;
     this.ball = ball;
   }

   this(Box!Dim box) {
     this.type = DomainType.Box;
     this.box = box;
   }

   this(CsgDiff!Dim csgDiff) {
     this.type = DomainType.CsgDiff;
     this.csgDiff = csgDiff;
   }

   void doSomething() {
     switch (type) {
     case DomainType.Ball:
       ...
       break;
     case DomainType.Box:
       ...
       break;
     case DomainType.CsgDiff:
       ...
       break;
     }
   }
}
```
Is there some way I can reduce the amount of boilerplate using D, 
i.e. generate most of this code at compile time?

For what it's worth, I had checked out `SumType` as an 
alternative to this mess, but it doesn't play nicely with 
recursively defined types.


More information about the Digitalmars-d-learn mailing list