Array of templated classes

JAnderson ask at me.com
Mon Aug 18 08:21:03 PDT 2008


tsalm wrote:
> Hello,
> 
> Does somebody know or have a way to do this :
> 
> /* --- BEGIN ---*/
> class MyClass(T) {T myData;}
> 
> void main()
> {
>   MyClass[] myArray;
> }
> 
> /* ---  END  --- */
> 
> Thanks in advance for your help.
> TSalm

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


More information about the Digitalmars-d-learn mailing list