Is it possible to store different generic types in ex. an

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 12 12:54:01 PST 2016


On 11/09/2016 07:46 AM, Is it possible to store different generic types? 
via Digitalmars-d-learn wrote:
> On Wednesday, 9 November 2016 at 15:44:59 UTC, Is it possible to store 
> different generic types? wrote:
>> Is it possible to store different generic types in ex. somekind of 
>> container such as an array, hashtable etc.
>>
>> Let's say we got
>>
>> class Foo(T) {
>>     ...
>> }
>>
>> Would it be possible to store something like
>>
>> Foo[] foos; // Where Foo of course should allow any generic version 
>> of Foo
>>
>> Ex.
>>
>> Foo!int and Foo!string should both be able to be stored inside the 
>> array.
>>
>> If so how would one construct an array like that or is there some 
>> other container that may be able to do it?
>
> I'm aware that I could have Foo inherit a base class and then use 
> casting, but I would like to avoid casting if possible.
>
You don't necessarily have to do casting if all of the objects that you 
are going to store use the same methods for the purposes that you are 
going to use them.  Just craft an interface that they all implement and 
inherit from that.  But if they don't all implement all the methods you 
are going to need, you can't avoid casting unless you do something like:
1) create a dummy class (I don't *think* an abstract class would work) 
that implements all the methods you are going to need with dummy methods.
2) inherit all the classes you are going to use from that class
3) be sure to use override on the methods that are actually implemented.

Even then I'm not sure this would work.  Since you are doing something like:
Dummy[Key]  stuff;
  when you retrieve an item from stuff, what you retrieve will be the 
actual item, but the system will probably think it's a Dummy unless you 
properly cast it.  So go with the interface approach, even if that means 
implementing dummy methods for some of the classes. (OTOH, I haven't 
actually *tried* that inherit from a common class...it might work.  I'd 
just bet against it without casting.)

The basic idea here is that all the objects that you store have to 
implement all the methods that you are going to use on any of them, but 
the implementations can be something like:
void method1()    {assert (false, "You should never come here"); }



More information about the Digitalmars-d-learn mailing list