Question about: ("1.1").to!int;
matheus at gmail.com
Fri Oct 23 16:59:06 UTC 2020
On Friday, 23 October 2020 at 13:57:41 UTC, Joseph Rushton
> On Wednesday, 21 October 2020 at 22:50:27 UTC, matheus wrote:
>> 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?
> The thing is, that's a great way for hard-to-identify bugs to
> creep into code. In these cases:
> 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
> ... then what the programmer wants is unambiguous. In the
> first case it's just converting int => int. In the second,
> it's converting from a string that unambiguously represents an
> integer value, to an int. And in the third, it's converting
> _at programmer request_ from a double to an int (which has a
> well-defined behaviour).
> However, if ("1.1").to!int were to work, this would be the `to`
> function making a judgement call on how to handle something
> ambiguous. And while that judgement call may be acceptable for
> your current use-case, it won't be for others.
I got it everything you said, but like a said previously:
(1.1).to!int vs ("1.1").to!int
One is a decimal literal while the other is a string
representation of a decimal.
To be honest I think the function is already making a judgment
call when I do (1.1).to!int and returns 1, I really fail to see
the difference when is ("1.1").to!int.
I agree with user1234: "The third case is just like `cast(int)
1.1` it's not _at programmer request_ from my point of view, it's
just that the `to` template has not be more restrictive than the
D `cast` expression. `to` should do at least what a `cast` do and
do more when there's no rule for the two types that are involved."
> In particular, if `to` just accepted any string numerical
> representation for conversion to int, how could the caller
> explicitly _exclude_ non-integer input, if that is their
Well since the caller is handling a string, shouldn't the caller
verify the content before any conversion?
Because a string may contain a integer, decimal representation or
Finally I don't want to make a fuss of it, I just thought it was
a bit weird but it can be solved easily.
More information about the Digitalmars-d-learn