For example, to convert the string "123" into an equivalent integer
value, you would use:
1
|
auto v = to!(int)("123");
|
You may also specify a default value which should be returned in the
event that the conversion cannot take place:
1
|
auto v = to!(int)("abc", 456);
|
The function will attempt to preserve the input value as exactly as
possible, given the limitations of the destination format. For
instance, converting a floating-point value to an integer will cause it
to round the value to the nearest integer value.
Below is a complete list of conversions between built-in types and
strings. Capitalised names indicate classes of types. Conversions
between types in the same class are also possible.
1
2
3
4
5
6
7
|
bool <-- Integer (0/!0), Char ('t'/'f'), String ("true"/"false")
Integer <-- bool, Real, Char ('0'-'9'), String
Real <-- Integer, String
Imaginary <-- Complex
Complex <-- Integer, Real, Imaginary
Char <-- bool, Integer (0-9)
String <-- bool, Integer, Real, Char
|
Conversions between arrays and associative arrays are also supported,
and are done element-by-element.
You can add support for value conversions to your types by defining
appropriate static and instance member functions. Given a type
the_type, any of the following members of a type T may be used:
1
2
|
the_type to_the_type();
static T from_the_type(the_type);
|
You may also use "camel case" names:
1
2
|
the_type toTheType();
static T fromTheType(the_type);
|
Arrays and associative arrays can also be explicitly supported:
1
2
3
4
5
6
7
8
9
10
11
|
the_type[] to_the_type_array();
the_type[] toTheTypeArray();
static T from_the_type_array(the_type[]);
static T fromTheTypeArray(the_type[]);
the_type[int] to_int_to_the_type_map();
the_type[int] toIntToTheTypeMap();
static T from_int_to_the_type_map(the_type[int]);
static T fromIntToTheTypeMap(the_type[int]);
|
If you have more complex requirements, you can also use the generic to
and from templated members:
1
2
|
the_type to(the_type)();
static T from(the_type)(the_type);
|
These templates will have the_type explicitly passed to them in the
template instantiation.
Finally, strings are given special support. The following members will
be checked for:
1
2
3
4
|
char[] toString();
wchar[] toString16();
dchar[] toString32();
char[] toString();
|
The "toString_" method corresponding to the destination string type will be
tried first. If this method does not exist, then the function will
look for another "toString_" method from which it will convert the result.
Failing this, it will try "toString" and convert the result to the
appropriate encoding.
The rules for converting to a user-defined type are much the same,
except it makes use of the "fromUtf8", "fromUtf16", "fromUtf32" and
"fromString" static methods.
This module contains imports to other Tango modules that needs
semantic analysis to be discovered. If your build tool doesn't do this
properly, causing compile or link time problems, import the relevant
module explicitly.