Question about: ("1.1").to!int;
user1234
user1234 at 12.de
Fri Oct 23 14:16:50 UTC 2020
On Friday, 23 October 2020 at 13:57:41 UTC, Joseph Rushton
Wakeling wrote:
> 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.
>
> 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
> use-case?
>
> So it's far better to require you, as the programmer, to make
> what you want unambiguous and explicitly write code that will
> (i) deserialize any numerical string that is acceptable to you
> and (ii) convert to integer.
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.
More information about the Digitalmars-d-learn
mailing list