how to define opCast outside class

Jonathan M Davis jmdavisProg at gmx.com
Sat Mar 30 00:21:43 PDT 2013


On Friday, March 29, 2013 23:57:56 Timothee Cour wrote:
> version(good) works.
> version(bad) does not.
> Can we make std.conv.to work for out-of-class opCast?
> Use case: same reason as UFCS, where we don't wanna define all methods
> inside class def, leading to possible extensions later.
> Currently this IS a problem when class A is in a library over which we
> have no control and a user defined class B wants to cast from A.
> 
> ----
> import std.conv;
> struct B{ int x;}
> struct A{
>     int x;
>     version(good)
>     auto opCast(T)() {return B(x);}
> }
> version(bad)
> auto opCast(T)(A a) {return B(a.x);}
> void main(){    auto b=to!B(A.init); }
> ----

If that's what you want to do, create a constructor on B which takes an A. As 
long as you're in control of one of the types, you can either declare the 
appropriate opCast or the appropriate constructor (which one depending on 
which direction you're trying to do the conversion in and which one you have 
control over). The only time that you're out of luck is when you don't have 
control over the API of either type.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list