Cast Object - get null

Jonathan M Davis jmdavisProg at gmx.com
Wed Apr 18 15:15:03 PDT 2012


On Wednesday, April 18, 2012 20:02:32 Namespace wrote:
> > 1. opCast doesn't do an implict cast. You'll have to cast to
> > get == to work.
> > 
> > 2. If you really have a static opCall, then the new isn't
> > necessary.
> > 
> > 3. You need to return from opCast. You're just declaring a
> > local variable.
> > 
> > 4. You need to import std.traits, or using Unqual will cause
> > the template
> > constraint to fail.
> > 
> > - Jonathan M Davis
> 
> 1. What have i to cast explicit? I thought that does the
> overloaded opEquals for me?

Since you're dealing with classes, it might work, since it takes Object. But 
then your opEquals is going to have to be able to cast to the appropriate type 
internally. If they were structs, it definitely wouldn't work, and in general, 
you're going to have to cast explictly when you want to convert something. 
Implicit conversions are relatively rare in D, which can be annoying at times, 
but it also reduces bugs. opCast is for explicit uses of cast(T) and does not 
do implicit conversions.

To do implicit conversions, you'd need to use alias this, but that wouldn't 
help you in this case, because you can currently only have one alias this per 
type (though you should be able to have multiple eventually), and even if you 
could have multiple, you'd need to declare one for every implicit conversion, 
which would be problematic with a templated type like you're dealing with 
(feasible, but definitely verbose).

> 2. See my post above.
> 3. I return with "return U(this.x, this.y);" that is not a local
> variable, imo.

Your latest example was

U opCast(U)() const
 if (is(Unqual!U == Vector2D!byte) ||
 is(Unqual!U == Vector2D!ubyte) ||
 is(Unqual!U == Vector2D!short) ||
 is(Unqual!U == Vector2D!ushort) ||
 is(Unqual!U == Vector2D!int) ||
 is(Unqual!U == Vector2D!uint) ||
 is(Unqual!U == Vector2D!long) ||
 is(Unqual!U == Vector2D!ulong) ||
 is(Unqual!U == Vector2D!float) ||
 is(Unqual!U == Vector2D!double) ||
 is(Unqual!U == Vector2D!real))
 {
 U v = new U(this.x, this.y);
 }

There's no return there.

> 4. Of course i import it, but it is implicit import if i import
> std.stdio.

No, it doesn't. If it does, it's an import bug. std.stdio does not publicly 
import std.traits. You need to import it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list