D is a strongly typed language, which means converting between types often has to be done explicitly. The language's built-in cast
operator only works when the types are already mostly compatible, for example int
to short
, or in cases where the user has defined an opCast
function. This doesn't cover the very common need of converting strings to integers and vice versa. That's where Phobos' std.conv
module is helpful.
Now it's time to perform type conversions by executing the following steps:
std.conv
.to
function as follows:import std.conv; auto converted = to!desired_type(variable_to_convert);
This is pretty simple, and it works for a lot of types.
auto a = to!int("123"); // a == 123
That's all you have to do!
The std.conv.to
function strives to be a one-stop shop for type conversions. The to
function isn't just one function. It is actually a family of functions from a template, one body that is parameterized on a list of compile-time arguments. That's why it has the !
operator in the name. In D, you pass two sets of arguments to a function template: a compile-time argument list and a normal runtime argument list. The syntax is as follows:
function_name!(compile, time, arguments)(run, time, arguments);
If you're familiar with C++, this is similar to the function_name<type, list, here>(arguments, here);
function of that language. D chose !()
over <>
because it has less lexing ambiguity. Compile-time arguments are similar to runtime arguments, so they look similar too.
If there is only one compile-time argument and it is syntactically simple (made up of only one token, for example, int
, string
, or object
, but not const(int)
or mymodule.Something
), the parentheses around the compile-time argument are not necessary. The to!int
function is equivalent to to!(int)
.
The compiler can often figure out compile-time arguments automatically if a runtime list is provided. This is called implicit function template instantiation (IFTI). In fact, this is how std.stdio.writeln
works; you can pass it any arguments you want, and it automatically converts them to strings and prints them out. Try the following line of code:
writeln!(int)(10); // works!
The reason writeln
converts variables to string is that like to
, it is a template function. D's templates let you write functions that generically handle a variety of types at once with convenient syntax. Phobos uses them extensively.
3.147.83.176