Overloading opCast with multiple types

Jarrett Billingsley kb3ctd2 at yahoo.com
Sun Oct 1 08:24:50 PDT 2006


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

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]; 





More information about the Digitalmars-d mailing list