Array/collection of templated class

Derek Parnell derek at psych.ward
Thu Apr 20 01:08:32 PDT 2006


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.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocracy!"
20/04/2006 5:51:52 PM



More information about the Digitalmars-d mailing list