std.conv.to vs. casting

monarch_dodra monarchdodra at gmail.com
Thu Jul 4 01:14:58 PDT 2013


On Thursday, 4 July 2013 at 06:18:21 UTC, CJS wrote:
> I'm having trouble understanding the difference between casting 
> and std.conv.to. Any help?

Casting merely changes the "observed type", whereas "to" does a 
deep conversion.

Observe:

----
import std.stdio;
import std.conv;

void main()
{
     int[] ints  = [1, 2, 3];
     auto bytes1 = cast(ubyte[])(ints);
     auto bytes2 = to!(ubyte[])(ints);
     writeln(bytes1);
     writeln(bytes2);
}
----
[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]
[1, 2, 3]
----

To is very useful to do "true" type conversion. It can change 
string width. Finally, "to" is able to do string interpretation. 
EG:

----
import std.stdio;
import std.conv;

void main()
{
     int[] ints  = to!(int[])("[1, 2, 3]");
     writeln(ints);
}
----
[1, 2, 3]
----

To is very convenient because it is a "one stop shop": It doesn't 
matter what you want to do: "to" will do it. You don't need to 
mix/match calls to atoi/itoa/encode/decode etc. Furthermore, it 
is safe: if anything fails, to will throw. It will also throw if 
you overflow:

----
import std.conv;

void main()
{
     int a = 500;
     ubyte b = cast(ubyte)(a); //No problem here: Silent overflow
     ubyte c = to!ubyte(a);    //Runtime overflow exception
}
----

Hope that helps :)


More information about the Digitalmars-d-learn mailing list