Meta-programming: iterating over a container with different types

Claude via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Sep 23 02:21:56 PDT 2016


It's more a general meta-programming question than a specific D 
stuff.

For an entity-component engine, I am trying to do some run-time 
composition: registering a certain type (component) to a 
structure (entity).

I would like to know how I can iterate an entity and get the 
different type instances registered to it.

Here is a simple example to clarify:

class Entity
{
   void register!Component(Component val);
   void unregister!Component();
   Component getComponent!Component();

   //iterating over the components (?!??)
   void opApply(blabla);
}

unittest
{
   // registering
   auto e = new Entity;
   e.register!int(42);
   e.register!string("loire");
   e.register!float(3.14);

   assert(e.getComponent!float() == 3.14); // that is OK

   // the code below is wrong, but how can I make that work??
   foreach (c; e)
   {
     writeln(c); // it would display magically 42, "loire" and 3.14
                 // and c would have the correct type at each step
   }
}


More information about the Digitalmars-d-learn mailing list