Question about: ("1.1").to!int;
Jack
jckj33 at gmail.com
Sun Oct 25 03:42:32 UTC 2020
On Wednesday, 21 October 2020 at 22:50:27 UTC, matheus wrote:
> Hi,
>
> import std.stdio, std.conv;
> void main(string[ ] args) {
> auto a = (1).to!int; // this works
> auto b = ("1").to!int; // this works
> auto c = (1.1).to!int; // this works and c = 1
> auto d = ("1.1").to!int; // Doesn't work
> }
>
> The forth line gives me:
>
> std.conv.ConvException@/usr/include/dlang/dmd/std/conv.d(1898):
> Unexpected '.' when converting from type string to type int
> ----------------
> ??:? pure @safe int std.conv.toImpl!(int,
> immutable(char)[]).toImpl(immutable(char)[]) [0x55de76d9b4d7]
> ??:? pure @safe int
> std.conv.to!(int).to!(immutable(char)[]).to(immutable(char)[])
> [0x55de76d99a17]
> ??:? _Dmain [0x55de76d9986e]
>
> Question:
>
> Since (1.1).to!int = 1, shouldn't the string value
> ("1.1").to!int at least try to convert to float/double and then
> to int?
>
> Because for what I see "to!int" converts from: int,real but in
> case of string only when it is a integer representation?
>
> Matheus.
In first case you asked to convert a float (inferred by templace
function) to int in the second case, you asked for the function
"convert this string contaning a set of digits to an int for me".
Doesn't make sense do something else than the asked. D has static
if() and a nice way to do type comparasion at compile time. It
does optimize things alot.
I haven't read the to source code, but consider it may use the
idea like this:
auto to(T, T2)(T2 source)
{
// you asked for int, doesn't makes sense consider a float
here.
// that would waste time checking for floats when you
programmer's requested
// was clear: an integer.
static if(is(T == int) && is(T2 == string))
{
int v = 0;
foreach(c; source)
v = v * 10 + c - '0';
return v;
}
// the string to float point conversion algorithm
static if(is(T == float) && is(T2 == string))
{
/* ... */
}
static if(is(T == int) && is(T2 == double))
{
return cast(int)source;
}
assert(0, "unknow type");
}
More information about the Digitalmars-d-learn
mailing list