June 08, 2004
In C++, the statement:

>       // given A a
>       B b = (B)a;

might call the cast operator, that is,

>       A::operator B()

In D, we have that covered. We have opCast(). But if class A does not define a cast to B, then it might /instead/ call

>       new B(a)

Now this is brilliant, because WITHOUT this trick, casts can only ever work in one direction. That is, if you can cast from A to B, you almost certainly can't cast from B to A, unless both A and B were written with each other in mind.

Now, I'm not suggesting that we do it quite that way. Reusing the constructor automatically might lead to too much confusion in some circumstances. But with a small change to the language (and this syntax is only a suggestion) we could allow it if explicitly stated. I would like to be able to do something like:

>       class Int
>       {
>           castable this(int x);  // syntax just a suggestion
>       }

to allow users to do:

>       // Given int a
>       Int a = cast(Int) b;

The intended meaning is that the constructor works normally, but will also be called as a result of trying to cast something to my class. Because, obviously, it is beyond my power to add a cast operator to int!

Arcane Jill