Array/collection of templated class

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


Derek Parnell wrote:
> On Thu, 20 Apr 2006 02:24:17 -0500, 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?
> 
> 
> Does this help ... ?
> 
> // ----------------------------
> import std.stdio;
> import std.boxer;
> 
> class Foo (T) {
>    public this (T a_value) { p_value = a_value; }
> 
>    public T value () { return p_value; }
>    private T p_value;
>  }
> 
> 
> void main ()
> {
>    Box[] arr;
> 
>    arr ~= box(new Foo!(int)(1));
>    arr ~= box(new Foo!(real)(2.345));
>    arr ~= box(new Foo!(char[])("test"));
> 
>    foreach(int i, Box b; arr)
>    {
>        if (unboxable!(Foo!(int))(b) )
>            writefln("%2d  int: %s", i, (unbox!(Foo!(int))(b)).value);
>        else if (unboxable!(Foo!(real))(b) )
>            writefln("%2d real: %s", i, (unbox!(Foo!(real))(b)).value);
>        else if (unboxable!(Foo!(char[]))(b) )
>            writefln("%2d char[]: %s", i, (unbox!(Foo!(char[]))(b)).value);
>    }
> }
> // ----------------------------
> 
> Remember to compile with '-release' because of the 'std.boxer' issue in
> Phobos.
> 

Sure, std.boxer will make the array work, but I would still have to be able to get the 
signature in order to unbox it.  This is a system with arbitrary templates.  It works for 
me in other cases; but now I'm wanting to provide an enumeration (the other method is to 
retrieve by name).

Plus the whole '-release' thing is a little annoying.  ;)  I hope Walter comes up with a 
genius solution for that soon.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list