D language cast operator overload problem
I'm playing with D2 at the moment, I would like to write some simple program but i'm stuck with operator cast overload...I have a Vector class 开发者_运维问答that can be cast to Normal :
class Vector {
public float x,y,z;
this(in float x, in float y, in float z){
this.x = x;
this.y = y;
this.z = z;
}
//..............
Normal opCast(T)() if (is(T == Normal)){
return new Normal(this.x,this.y,this.z);
}
}
If i write something like
immutable Vector v = cast(immutable(Vector))new Vector(0F, 0F, 0F);
the compiler complains that :
"template instance opCast!(immutable(Vector)) does not match template declaration opCast(T) if (is(T == Normal))"If I omit the cast:
immutable Vector v = new Vector(0F,0F,0F);
the message changes, but the program does not compile:
"cannot implicitly convert expression (new Vector(0F,0F,0F)) of type Vector to immutable(Vector)"If I omit the cast operator overload in the Vector class all compile just fine.
Put in a different way...How can I assign or cast an instance to an immutable 'var'?
you should not overload opCast
normally.
commonly methods named toTypename are used for object that knows how to convert itself to another.
Normal toNormal () { return new Normal (x, y, z); }
You have two solutions:
A pretty solution is what Trass3r already mentioned in his comment: Treat
immmutable(Vector)
as its own data type (it is), and call its constructor.A somewhat uglier solution is to use
assumeUnique()
on the object you want to cast. I think you might need to import a library (std.exception
, if I'm not wrong).
精彩评论