Cast Object - get null

Jonathan M Davis jmdavisProg at gmx.com
Wed Apr 18 10:28:05 PDT 2012


On Wednesday, April 18, 2012 19:15:21 Namespace wrote:
> > one another, you're going to need to overload opCast.
> > 
> > - Jonathan M Davis
> 
> Thanks for your answer.
> I have tried to overload opCast in this way:
> U opCast(U)() const {
> return U(this.x, this.y);
> }
> 
> But then i get this compiler error
> cast.d(36): Error: no property 'opCall' for type 'object.Object'
> cast.d(299): Error: template instance
> cast.Vector2D!(short).Vector2D.opCast!(Obj
> ect) error instantiating
> cast.d(36): Error: no property 'opCall' for type 'object.Object'
> cast.d(299): Error: template instance
> cast.Vector2D!(float).Vector2D.opCast!(Obj
> ect) error instantiating
> 
> The dokumentation of opCast is very short, did i understand
> opCast wrong?

You're dealing with a class, so you need to use new. As it stands, you're 
trying to call an overload static opCall on U, and presumably, you haven't 
declared one.

Ideally, you'd also have a template constraint restricting the cast to the 
types that you want to be able to cast to, but since you're dealing with a 
templated type, that can be a bit tricky. One (somewhat ugly) option would be 
to do something like

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))
{
 return new U(x, y);
}

Another would be to have an enum on the type indicating that it's an 
instantiation of your Vector2D template (e.g. isVector2D).

U opCast(U) const
 if(__traits(compiles, U.isVector2D))
{
 return new U(x, y);
}

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list