yes, that was precisely the case I was concerned about: two types for which I don't have control over. That's a common enough case. My current workaround is to use a ---- T1 to2(T1,T2)(T2 a) ---- which is ugly as it only works for *that* conversion and doesn't play well with the rest of phobos (eg: won't work recursively, if I want to convert a vector of A to a vector of B).
I could also reimplement a whole std.conv.to (say, to2) that also checks for out of class opCast, but I don't see what's so bad about having it in std.conv.to. >> This was discussed many times, even recently enhancement request was created >> in bugzilla Do you have any link? Thanks! On Sat, Mar 30, 2013 at 12:21 AM, Jonathan M Davis <[email protected]> wrote: > 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
