Array/collection of templated class

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Apr 20 11:50:34 PDT 2006


This actually does /almost/ work, except that I can't use the TypeInfo object to 
redescribe the template instance.  There almost needs to be some kind of covariance across 
template instances.

-- Chris Nicholson-Sauls

BCS wrote:
> Might this work?
> 
> abstract class Foo
> {
>     abstract TypeInfo TypeOf();
> }
> 
> class FooT (T) : Foo
> {
>     public this (T a_value) { p_value = a_value; }
> 
>     public T value () { return p_value; }
> 
>     TypeInfo TypeOf() { return typeid(T); }
> 
>     private T p_value;
> }
> 
> void main ()
> {
>     Foo[] arr = new Foo[3];
> 
>     arr[0] = new FooT!(int)(123);
>     arr[1] = new FooT!(char[])("hello world");
>     arr[2] = new FooT!(Object)(arr[0]);
> }
> 
> 
> Chris Nicholson-Sauls wrote:
> 
>> I'm working on a project of mine, and I came across this little 
>> problem.  Now, it may well be that the solution is staring me in the 
>> face, but I just can't seem to come up with a feasible solution to 
>> this: I can't have an array of a templated class.
>>
>> To illustrate:
>>
>> ########## foo.d
>> # class Foo (T) {
>> #   public this (T a_value) { p_value = a_value; }
>> #
>> #   public T value () { return p_value; }
>> #   private T p_value;
>> # }
>> #
>> # void main () {
>> #   Foo[] arr;
>> # }
>>
>> This will give the error:
>> foo.d(9): class foo.Foo(T) is used as a type
>>
>> Now, granted, I expected this.  But I'm at a loss as to what to do.  
>> Sure, if I had a way of knowing the signatures of the template 
>> instances I could just use "Object[]" decleration and a cast() 
>> expression on the lookup, but this is for a system where I usually 
>> won't know.
>>
>> Ideas?
>>
>> -- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list