toImpl deprecated, use opCast instead?

Jonathan M Davis jmdavisProg at gmx.com
Mon Jun 11 14:52:52 PDT 2012


On Monday, June 11, 2012 23:11:06 Era Scarecrow wrote:
> On Monday, 11 June 2012 at 18:19:21 UTC, Manu wrote:
> > On 10 June 2012 03:42, Jonathan M Davis <jmdavisProg at gmx.com>
> > 
> > wrote:
> >> On Sunday, June 10, 2012 02:26:36 timotheecour wrote:
> >>> What is the recommended approach when we have no control over
> >>> classes A or B (cf from 3rd party) to convert A to B? It
> >>> seems UFCS doesn't work in that case. Could you please
> >>> provide an example code? Thanks!
> >> 
> >> If you want to convert between two types and you don't control
> >> the definitions of either, and neither of them have any
> >> functions which will convert from one to the (including
> >> constructors, opCast, etc.), then you're just going to have to
> >> write a function to do it. It's not gonig to work with
> >> std.conv.to or casting, but you can write such a function just
> >> like you can write any other function.
> >> 
> >> A convertBToA(B b) {...}
> >> 
> >> I don't think that there's anything else that you _can_ do.
> > 
> > That's very problematic for generic programming :/
> 
> Is there any way to do implicit conversion? Or a specific call
> based on the object just being 'called'?

The only way to do implicit conversions is with alias this, which must be part 
of the type being converted. If you're trying to add conversions without 
altering either of the types being converted, you need a function to do the 
conversion, and it can't be implicit and won't be recognized by std.conv.to. 
There's certainly nothing stopping you from creating your own conversion 
functions, however, and if you templatized it, and defined the appropriate 
overloads for it for each of the types that you want to convert, you could 
then use it in generic code.

But none of D's conversion constructs (either implicit or explicit) can be 
defined externally to a type. Any externally defined conversions are pure 
library code and thus cannot be implicit, and since anything you define 
externaly isn't standard, standard library constructs such as std.conv.to 
won't use it either.

- Jonathan M Davis


More information about the Digitalmars-d mailing list