Cast Object - get null

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


On Wednesday, April 18, 2012 18:58:42 Namespace wrote:
> override bool opEquals(Object o) const {
> if (o is null) {
> return false;
> }
> 
> writeln(o); // write: cast.Vector2D!(float).Vector2D
> 
> Vector2D!(T) vec = cast(Vector2D!(T)) o;
> 
> writeln(vec); // write: null
> // ...
> 
> It seems the cast fail, but the question is: why?
> 
> Here my test context:
> 
> void main() {
> alias Vector2D!(short) Vector2s;
> alias Vector2D!(float) Vector2f;
> 
> Vector2f vf = Vector2f(23, 42);
> 
> Vector2s vs = Vector2s(vf);
> 
> writefln("vs.x: %d, vs.y: %d", vs.x, vs.y);
> 
> Vector2s vs2 = Vector2s(23, 42);
> 
> if (vs2 == vf) {
> writeln("equal");
> }
> }
> 
> Vector2D is my own class. If i compare vs2 with vs it works fine,
> but if i compare vs or vs2 with vf, the cast fail and i get a
> null-reference. How can i avoid this?

Vector2s and Vector2f are completely unrelated types. Templated types have no 
relation to one another even if they're generated from the same template 
unless they have the same template arguments. If you have

class Foo(T)
{
 T value;
}

and you do

auto a = new Foo!int;
auto b = new Foo!float;

it's like you copy and pasted to create two new classes:

class FooInt
{
 int value;
}

class FooFloat
{
 float value;
}

and those classes aren't related at all. They could have a common base class 
(and do with Object) if you declared them that way

class Foo(T) : Base
{
 T value;
}

and then they could both be cast to the base type, but they can't be cast to 
each other, because neither is derived from the other.

If you want to be able to cast your Vector2D!int and Vector2D!float types to 
one another, you're going to need to overload opCast.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list