www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - how to define opCast outside class

reply Timothee Cour <thelastmammoth gmail.com> writes:
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); }
----
Mar 29 2013
parent "Maxim Fomin" <maxim maxim-fomin.ru> writes:
This was discussed many times, even recently enhancement request
was created in bugzilla. Try to search in archives (in briefly -
no, it is a bad idea, which has opposition, me included).
Mar 30 2013