Summary: Function to check whether will succeed
           Product: D
           Version: unspecified
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos

--- Comment #0 from Jonathan M Davis <> 2011-10-23 00:17:49 
PDT ---
In some cases, will complain at compile time that it can't do a
particular conversion, but in others it depends on runtime values. For
instance, to!int("hello world") will fail at runtime. Currently, the only way
to know if such a conversion will succed is to call and then catch
the ConvException when it fails. However, unfortunately, exception handling is
_very_ expensive in D (as in an expression which throws an exception is more
than 100x slower than one that doesn't), so in cases where there's a good
chance that will fail (or when you just want to check whether it
will succeed or not) are _very_ expensive.

I would very much like to see a function in which returned whether will succeed or not so that it will be efficient to check whether will succeed or not. And actually, because it's not particularly
efficient to call such a function and then call (since that would
do the conversion twice - though that's still far more efficient than testing
with, since exceptions are so expensive), the function should
probably give the converted value as well if it succeeded.

For instance, we could have

bool tryTo(T, S)(S toConvert) {...}
bool tryTo(T, S)(S toConvert, out T result) {...}

The first version checks whether the conversion will succeed (probably doing
the full conversion) and returns whether it succeeded or not, whereas the
second version does the full conversion and not only returns whether it
succeeded or not, but it sets result to the result of the conversion (or T.init
upon failure - though out should do that automatically if result is never set
within the function).

We should probably have the same for std.conv.parse as well.

bool tryParse(Target, Source)(ref Source s) {...}
bool tryParse(Target, Source)(ref Source s, out Target result) {...}

It's probably not quite as useful for parse (particularly since tryParse would
still need to consume s in the first overload to be consistent), but it would
make parsing more efficient when parsing failures are common.

Regardless, tryTo would make dealing with _much_ more efficient in
cases where conversion failures are common.

Configure issuemail:
------- You are receiving this mail because: -------

Reply via email to