Question about: ("1.1").to!int;

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Fri Oct 23 13:57:41 UTC 2020


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.


More information about the Digitalmars-d-learn mailing list