struct subtyping?

bearophile bearophileHUGS at
Sun Oct 24 15:47:17 PDT 2010


> But for any reason, this logic is not pushed to the point of providing type hierarchy by subtyping. It would have been great for me, since much of the common functionality is generic. Without a type hierarchy, I need to duplicate it on each struct type, which is _bad_ (as any programmer knows ;-).
> I would like to learn about possible workarounds, or other alternative approaches to such problems, if ever you now any.

Beside the alias this answered by Simen kjaeraas, another option is to use template mixin to factorize common code, but then you will have to manage the hierarchy manually.

You may even add a common enum tag (present in all your structs as first field or among the fields of the root of your hierarchy) that encodes the type of the struct. Sometimes to save space you may find a way to encode this tag inside some other number or even pointer. I have done all this in D, and it's not handy, it's error-prone, and the language never helps you much. I have build a generic TaggedPointer struct, but often that's not the best solution.

It seems the Zen of the D language is to give you a safe high-level way to do something. If you refuse to use it then you are on your own, as in C, and the language doesn't catch your bugs. I don't love this much, but it helps keep the language simpler.

> (*) Oberon is rather close to D on this point:

Probably there are some other points where Oberon is similar to D.


More information about the Digitalmars-d-learn mailing list