Template bug?
Jarrett Billingsley
kb3ctd2 at yahoo.com
Mon Jan 29 21:06:32 PST 2007
"Artyom Shalkhakov" <artyom.sh at gmail.ru> wrote in message
news:epmho3$282d$1 at digitaldaemon.com...
> Hello everyone.
>
> I have a problem regarding D templates.
>
> This code doesn't work. I would like to know how do I get it up'n'running?
>
> struct temp_t( type ) {
> void setOwner( type *newOwner ) {
> owner = newOwner;
> }
>
> type *getOwner() {
> return owner;
> }
>
> protected {
> temp_t * head;
> temp_t * next;
> temp_t * prev;
> type * owner;
> }
> }
>
> class testClass_t {
> this( int d ) {
> data = d;
> tst.setOwner( &this );
> }
>
> int data;
> temp_t!( testClass_t ) tst;
> }
>
> void foo() {
> testClass_t bar = new testClass_t( 0x1234 );
>
> // what is the difference between '==' and 'is'?
> assert( ( *bar ).getOwner == bar ); // doesn't work
> }
There are a few things going wrong.
One, when you write "tst.setOwner( &this );", this sets the owner to the
address of a local variable. This is a Bad Thing. Remember that classes
are reference types, so they are implicitly pointers. So instead of making
your struct use pointers, just take all the *s out.
struct temp_t( type ) {
void setOwner( type newOwner ) {
owner = newOwner;
}
type getOwner() {
return owner;
}
protected {
temp_t * head;
temp_t * next;
temp_t * prev;
type owner;
}
}
Then in your class's constructor, use
tst.setOwner( this );
Lastly, this line:
assert( ( *bar ).getOwner == bar );
Doesn't even compile because (1) you cannot dereference bar because it's not
a pointer, it's a reference, and (2) there is no .getOwner property for the
testClass_t class. Instead, you should use:
assert( bar.tst.getOwner is bar);
And that brings me to my last point, the difference between 'is' and '=='.
'is' is used to see if two references (or pointers) point to the same
location. '==' is used to see if two things are equal. If you have two
class references, a and b, and you write
a == b
This is the same as writing
a.opEquals(b)
If a is null, this will get you a segfault. However, if you just want to
see if a and b are pointing to the same instance, use
a is b
Which is what you want to do in your example.
More information about the Digitalmars-d-learn
mailing list