www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Types as keys

reply Voitech <woipoi gmail.com> writes:
Hello, I'm having problem with converting from Java style coding 
to D, probably doing wrong something. I want to have a map 
(associative array) which will return specific object depending 
on provided key. Key is a type of other object. Let say i want to 
hold single instances of some kind of parser for each key object 

class BaseFooBar{}

class Foo:BaseFooBar{


class Bar:BaseFooBar{



Parser(T) :BaseParser{
abstract string parse(T value);
override string parse(Foo value){

override string parse(Bar value){

Parser[TypeInfo] container;
container~=new ParserOne();
container~=new ParserTwo();

Now i have some data Foo and some Bar in array and each one must 
be parsed using proper parser

parserFoobars(BaseFooBar[] values){

foreach(BaseFooBar foobar;values){
     BaseParser parser=container[typeid(foobar)];
Now i would have to cast check if parser is ParserOne or 
ParserTwo and then cast foobar to Bar or Foo depending on which 
parser has been retrieved. This has no sense ...  In Java i could 
place generic code in BaseParser and depending on FooBar type i 
will get proper parser from map, and values would be parsed 
without casting.

How to handle this correctly?
Jan 26 2016
parent Jakob Ovrum <jakobovrum gmail.com> writes:
On Tuesday, 26 January 2016 at 15:54:14 UTC, Voitech wrote:
 How to handle this correctly?
Make BaseParser the value type of the AA. Parser!Foo and Parser!Bar are subtypes of BaseParser. Unlike Java, just `Parser` is not a type but a template. It must be instantiated to create a type. Java implements generics differently from templates, with its own set of disadvantages and advantages.
Jan 26 2016