bearophile bearophileHUGS at lycos.com
Mon Apr 19 11:59:20 PDT 2010

Ellery Newcomer:

> Say I have a [struct] template T, which takes a param S.
> Any T!(S) satisfies a certain template constraint W, so I can use any 
> T!(S) the same way. I want to be able to store heterogeneous T!(S) in a 
> single list. Is there any good way to express the type for this?

In D the templates with their arguments create a Nominative type system, so they are all seen as distinct types:

So in D the standard, simpler and safer way to create a (flat) hierarchy of things that can be mixed in a container is to use the same strategy you use in Java, to create a base class/interface/abstract class, create a container of such base thing, and then populate it.

If you don't want objects, and you want templated structs, then you have to work more, and your code will probably be less safe. In your situation you can create a common struct, it can contain several common fields, or just a tag, this is the minimal:

enum FooTags { Tag1, Tag2, ... }

struct BaseFoo {
    FooTags tag;
    // few common attributes
    // few common methods

(That BaseFoo can also be a template mixin, then you can mix in this template at the top of all your derived structs.)

struct Foo1 {
    FooTags tag = FooTags.Tag1;

Then you have to read the tag and cast the pointer to the pointer of the correct type, in a switch if necessary...
If your structs are allocated from the C heap, and you have only up to 8 or 16 different structs, you can even use a tagged pointer, but you also need an aligned malloc wrapper. This saves the 1 or or 2 or 4 bytes for the tag.


More information about the Digitalmars-d-learn mailing list