On Saturday, 22 April 2017 at 12:14:26 UTC, Nordlöw wrote:
Have anyone tried to implement a variant of `std.conv.to` that
can be `nothrow @nogc` if the exception handling is replaced by
an extra second parameter (`defaultValue`) returned iff the
call to `to` throws?
There is common ifThrown template in Phobos:
https://dlang.org/phobos/std_exception.html#ifThrown
I think it's better to add nothrow ifThrown implementation if
needed.
As for me, for such cases, where input data can be not relevant,
is better to use Nullable type to indicate the error. In this
case, an input value equal to the default value does not cause
problems. Something like this:
import std.typecons: Nullable;
Nullable!T nullableTo(T, S)(S source)
{
import std.conv : to;
try return Nullable!T(source.to!T);
catch(Exception e) return Nullable!T();
}
T orElse(T)(Nullable!T n, T value){ return n.isNull() ? value :
n.get; }
unittest
{
assert(! "0".nullableTo!int.isNull);
assert("0.0".nullableTo!int.isNull);
assert("123.45".nullableTo!int.isNull);
assert("123".nullableTo!int.get == 123);
// And easy convertable to default value variant
assert("123.45".nullableTo!int.orElse(5) == 5);
}