Array of templated classes

tsalm tsalm at free.fr
Mon Aug 18 12:48:34 PDT 2008


Le Mon, 18 Aug 2008 17:21:03 +0200, JAnderson <ask at me.com> a écrit:

>>  Does somebody know or have a way to do this :
>>  /* --- BEGIN ---*/
>> class MyClass(T) {T myData;}
>>  void main()
>> {
>>   MyClass[] myArray;
>> }
>>  /* ---  END  --- */

> You can't do this directly because when you try to pull the data out you  
> have no idea what template type it is.  There are several ways which  
> might get you what you want.  You could use an interface...
>
> interface MyClassI
> {
> 	void ProccessData();
> }
>
> class MyClass(T) : MyClassI {T myData;  ProccessData() {...} }
>
> void main()
> {
> 	MyClassI[] myArray;
> }
>
> You could also get at the data using a dynamic cast and I wouldn't  
> recommend breaking polymorphism like that.
>
> Another way would be to use a void* however that means you will have to  
> dynamic cast.
>
> A third way is to have another template manage the data:
>
> class MyTemplateArray
> {
> 	MyClass(int)[] myArrayInt;	
> 	MyClass(float)[] myArrayFloat;	
> ...
> 	T Get(T : int)(int index) { return myArrayInt(index); }
> 	T Get(T : float)(int index) { return myArrayFloat(index); }
> ...
> }
>
> Although I'd reconsider the design if it comes down to that.
>
> -Joel


Thanks for those clear explanations.
I think using an interface could be the better way for me because I don't  
know the exact type of T when I get it on the array.


More information about the Digitalmars-d-learn mailing list