Array/collection of templated class
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Thu Apr 20 11:21:22 PDT 2006
Hasan Aljudy wrote:
> 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
>
>
> Hmm .. templates are generally used for things that you know at compile
> time, if you don't, well .. trying doing something different.
The reason I won't know, is because the template instances are built and made available by
various objects, independantly of each other. Consider this contrived example:
########## module somelib.d
# class Foo (T) {
# public this (char[] a_name, T* a_what) {
# p_name = a_name ;
# p_what = a_what ;
# }
#
# public char[] name () { return p_name ; }
# public T value () { return *p_what ; }
#
# private char[] p_name;
# private T* p_what;
# }
#
# class Bar {
# package int p_alpha ,
# p_beta ;
#
# public Foo[] wrap () {
# Foo[] result;
# result ~= new Foo!(int)(
# }
#
# public int doStuff () { /* ... */ }
# }
########## module someapp.d
# import std.stdio ;
# import somelib ;
#
# void main () {
# Bar mybar = new Bar ;
# Foo[] wbar = mybar.wrap ;
#
# while (mybar.doStuff)
# foreach (x; wbar)
# writefln("%s(%s)", x.name, x.value);
# }
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list