Facing problems with Class Properties

Steven Schveighoffer schveiguy at yahoo.com
Fri Dec 10 11:56:46 PST 2010


On Fri, 10 Dec 2010 11:35:50 -0500, d coder <dlang.coder at gmail.com> wrote:

> Greetings All
>
> I am trying to compile the following D2 code. The code giving compilation
> issues is the "this()" function of the class Foo. The constructor  
> basically
> tries to initialize all the data members of the class, of type BaseClass  
> and
> of type BaseClass array.
>
> I am using class property tupleof to iterate over members of the class.  
> Then
> I check the type of each member and if the member is a BaseClass array, I
> new all the elements of the array. Otherwise if the member is of the type
> BaseClass, I new it as it is.
>
> The issue is that when I try to compile the program, I get the error
> bug.d(10): Error: no property 'length' for type 'test.Bar'
>
> I am explicitly checking the field type, and I am making sure that the  
> field
> is an array type, before looking for its length. So I am not sure why  
> this
> error appears. Please guide me.
>
> Regards
> Cherry
>
> import std.stdio;
> class BaseClass { }
>
> class Bar: BaseClass { }
>
> class Foo: BaseClass {
>   this() {
>     foreach(i, f; this.tupleof) {
>       if (is (typeof(f) : BaseClass[])) {
> for (size_t j = 0; j < f.length; ++j) {
>   f[j] = new typeof(f[j]) ();
> }
>       }
>       if (is(typeof(f) : BaseClass)) {
> f = new typeof(f) ();
>       }
>     }
>   }
>   Bar instance1;
>   Bar instance2;
>   Bar [10] instances;
> }
>
> unittest {
>   Foo foo;
>   foo = new Foo;
> }

is(typeof(f) : BaseClass[]) is a compile-time construct, yet you are  
trying to use it at runtime.

I'm not even sure how this could compile.  I imagine that you could use a  
recursive template to deal with the tuple, but I didn't think you could  
use a foreach loop.

Is there a reason you can't directly reference the members?  After all,  
you are writing the class.

Another thing, is(T : U) simply means T is implicitly castable to U.  Due  
to a compiler bug, Bar[] is implicitly castable to BaseClass[].

is(T == U) ensures that the type is exact.

-Steve


More information about the Digitalmars-d-learn mailing list