Multiple opCasts

dsimcha dsimcha at yahoo.com
Sat Aug 23 12:21:53 PDT 2008


The discussion on builtin arrays and opImplicitCast has gotten me thinking,
why shouldn't it be possible to have more than one opCast (explicit cast)
definition?  Yes, it's impossible to overload a function by return type.
However, since the type that's being cast to is known at compile time and
explicitly specified in the cast syntax, it could easily be done with template
specializations.  For example, on the struct side:

struct Foo {
    T opCast(T : float)() {
        return 3.14159265;
    }

    T opCast(T : int)() {
        return 1;
    }
}

On the calling side:

Foo foo;
int i = cast(int) foo;  //equivalent to int i = foo.opCast!(int)().
float f = cast(float) foo;  //equivalent to float f = foo.opCast!(float)()



More information about the Digitalmars-d mailing list