Re: Types as keys

2016-01-26 Thread Jakob Ovrum via Digitalmars-d-learn

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.




Types as keys

2016-01-26 Thread Voitech via Digitalmars-d-learn
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?