toImpl deprecated, use opCast instead?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 8 02:12:41 PDT 2012


On Thursday, June 07, 2012 16:47:08 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?

As the documentation says:

$(RED Deprecated. It will be removed in August 2012. Please define $(D opCast)
      for user-defined types instead of a $(D to) function.
      $(LREF to) will now use $(D opCast).)

Previously, you defined a to function on your type to make it work with 
std.conv.to. Now, you define opCast. It allows std.conv.to to work with your 
custom opCasts and avoids issues like if you have both opCast and to defined on 
your type for the same conversion. As it's a user-defined opCast, rather than 
the built-in one, it's as safe as any function doing such a conversion would 
be. So, defining such an opCast is just fine, and it means that you can now use 
that opCast with std.conv.to instead of casting, which reduces the odds of 
something going wrong like having screwed up the the opCast declaration (e.g. 
opcast instead of opCast) and having the compiler use the built-in cast when 
you tell it to cast.

This change isn't asking you to use an explicit cast. It's merely asking you 
to define opCast rather than your own to in order to get your type to work with 
std.conv.to.

- Jonathan M Davis


More information about the Digitalmars-d mailing list