toImpl deprecated, use opCast instead?

Jens Mueller jens.k.mueller at gmx.de
Fri Jun 8 02:37:16 PDT 2012


Manu wrote:
> On 7 June 2012 17:09, Jens Mueller <jens.k.mueller at gmx.de> wrote:
> 
> > Manu wrote:
> > > Seriously?
> > >
> > > I perceive to!T and cast(T) as fundamentally different operations. How
> > can
> > > opCast correctly perform the role of to! ?
> > > cast() is a low level type cast, to! implies a conversion of some kind.
> > If
> > > you have a pointer type, I assume cast to operate on the pointer, and to!
> > > to perform a conversion of the thing it represents.
> > >
> > > to!int("12345")  or  cast(int)"12345"
> > > to!JSONValue(obj)  or  cast(JSONValue)obj
> > > cast(string)obj  <- appears to be a primitive cast operator, communicates
> > > nothing to me about the expected format of the string produced
> > >
> > > The cast approach feel really wrong to me...
> > >
> > > I need to do conversion between some fairly complex types. to! feels
> > > appropriate, but cast() just seems weird...
> > > Have I missed something?
> >
> > I think the passage you are referring to applies only when converting
> > from a user defined type to a built-in type.
> > If you have user defined types only the right approach is to define a
> > constructor in the target type I think.
> > Something like this:
> >
> > struct A {}
> > struct B {
> >        this(A a)
> >        {
> >        }
> > }
> >
> > to!B(A); // will use B's constructor
> >
> > I don't know what to do if you have no control over B (besides opCast or
> > providing a specialized to! template).
> >
> 
> I have no control over B.
> I thought the idea of toImpl() was to avoid having to specialise to! ?
> I generally liked the idea, except the name toImpl seems odd (what's
> 'implicit' about an explicit conversion function?)

Then I would go with defining opCast in A if you also need implicit
conversions from A to B. If you only want explicit conversions then
define to! for that particular conversion.
I think to! and toImpl! handle most of the (common) conversion use cases
but not the case you want.
Does this still look odd to you?

Jens


More information about the Digitalmars-d mailing list