Types as keys

Voitech via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 26 07:54:14 PST 2016


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 
types.

class BaseFooBar{}

class Foo:BaseFooBar{

...
}

class Bar:BaseFooBar{
....

}

BaseParser{}

Parser(T) :BaseParser{
abstract string parse(T value);
}
ParserOne:Parser!Foo{
override string parse(Foo value){
...
}

ParserTwo:Parser!Bar{
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?



More information about the Digitalmars-d-learn mailing list