2

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'?

Andrea
  • 21
  • 1
  • 2
    I think you should be able to do 'auto v = new immutable(Vector)(0f,0f,0f);' – Trass3r Jun 20 '11 at 21:27
  • 4
    "class Vector" is a supremely bad idea. I assure you, you do not want to force a memory allocation for every vector operation you perform. Use "struct Vector" instead. _Please_. – FeepingCreature Jun 21 '11 at 00:46

2 Answers2

1

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); }
Michal Minich
  • 2,387
  • 1
  • 22
  • 30
0

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).

user541686
  • 205,094
  • 128
  • 528
  • 886