Simplify some C-style code

Christian Köstlin christian.koestlin at gmail.com
Sun Jan 5 16:02:47 UTC 2025


On Wednesday, 25 December 2024 at 07:49:28 UTC, sfp wrote:
> 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.

What would speak against coming up with an interface 
(https://dlang.org/spec/interface.html) the only includes this 
`doSomething` method and then having `Ball`, `Box` and `CsgDiff` 
implementing that.
Almost no boilerplate involved, no manual union and type storing, 
but a virtual function call for `doSomething`.

It's "very" OOP, which gets less and less popular, but why not?

Kind regards,
Christian


More information about the Digitalmars-d-learn mailing list