Overloading opCast with multiple types

Kristian kjkilpi at gmail.com
Sun Oct 1 10:37:34 PDT 2006


On Sun, 01 Oct 2006 18:24:50 +0300, Jarrett Billingsley  
<kb3ctd2 at yahoo.com> wrote:
> "Kristian" <kjkilpi at gmail.com> wrote in message
> news:op.tgqne1b35xlco7 at mist...
>
> -------------------------------------------
> Anyway, I think the opCasts can also be implemented as follows:
>
> class Obj {
>      int opCast(out int dst) {return(dst = ...);}
>      Foo opCast(out Foo dst) {return(dst = ...);}
> }
>
> Or in some other way which don't complicate the implementation of
> compilers. (Of course, the previous syntax makes it cumbersome to call
> opCasts by yourself (e.g. "obj.opCast(tmp);"), but you're supposed to use
> cast statements anyway (e.g. "cast(int)obj").)
> --------------------------------------------
>
> Of course, with that method, something like
>
> Obj o = new Obj();
> func(cast(int)o);
>
> Wouldn't work, because there is no location to pass into the opCast; it's
> just a temporary.

Well yes, unless the compiler generates a temporary object that will be  
valid within the scope. For example, the previous example, will become:

     int _tmp;
     Obj o = new Obj();
     func(o.opCast(_tmp));

The syntax of opCast() is a matter of implementation only: which is the  
simpliest way for the compiler. If not, then the C++ styled operators  
could be used in D also. BTW, you could also have:

class Obj {
      int opCast(int) {return(...);}
      Foo opCast(Foo) {return(...);}
}

Parameters are just used to overload the operators.


>
> I've gotten quite used to just having ".toXXX" or ".asXXX" methods.  It  
> can
> be far more obvious what you're doing, and you can pass additional
> parameters to it unlike a cast.  That, and it can look nicer too:
>
> int x = (cast(ArrayType)object)[4];
>
> vs
>
> int x = object.asArrayType[4];
>
>

Yep, I also prefer such functions over cast statements.
But if D would have implicit type conversion with multiple opCasts, then  
you could just do "x = y;". Would this be a good thing?... I don't know.  
(Surely it would be less informative, if nothing else.)



More information about the Digitalmars-d mailing list