Array/list of objects of different type but with same interface

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Wed Jun 20 14:01:27 PDT 2012


Hello all,

I'm considering a rewrite of some old C/C++ simulation code in D.  This code is 
a "stock market" game where lots of different agents with different strategies 
compete and try to outdo one another at trading.

What I'm puzzling over is how to effectively store the collection of agents. 
These will be arbitrary in number (and agents might in principle be created or 
destroyed during the game), will all have the same interface, but will have 
different implementations -- some may use look-up tables, some may be controlled 
by neural networks, etc. etc.

When I originally wrote this in C, I just used an array of pointers to agents. 
In C++ I did something similar, defining an agent class of which all 
implementations were subclasses.

I'm just wondering what might be the best and most idiomatic way to do this in 
D.  My likely agent design will be a "policy class" style,

     struct Agent(alias X, alias Y, ...)
     {
         mixin X;
         mixin Y;
         // etc...
     }

... with template mixins to implement the individual components that vary by 
agent type.  The public interface will be identical for all agents.

What I can't work out is how to store a collection of these agents in an array 
or similarly efficient container.  Can anyone advise?

Thanks and best wishes,

     -- Joe


More information about the Digitalmars-d-learn mailing list