[Issue 17896] New: Alternate version of std.conv.to which returns Nullable

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Oct 12 03:30:52 UTC 2017


https://issues.dlang.org/show_bug.cgi?id=17896

          Issue ID: 17896
           Summary: Alternate version of std.conv.to which returns
                    Nullable
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: phobos
          Assignee: nobody at puremagic.com
          Reporter: issues.dlang at jmdavisProg.com

std.conv.to throws a ConvException when it runs into a problem doing a
conversion. In many cases, this is great, but in some cases, it really isn't,
and it can lead to code like this

int i;
try
    i = to!int(str);
catch(ConvException)
{
   ...
}

which is inefficient and verbose - particularly if there's a high chance that
the conversion will fail. Exceptions make a lot of sense when it's reasonable
to expect the conversion to succeed, but when there's a high chance that it
won't, they just make things worse. So, ideally, we'd have an alternative that
returned a Nullable, e.g.

auto i = tryTo!int(str);
if(i.isNull)
{
   ...
}

This would also provide a superior alternative to std.string.isNumeric, because
it would essentially make it a one-liner to ask whether a conversion would
succeed. e.g.

if(!tryTo!int(str).isNull)
{
    ...
}

and it would work for more than just numeric types.

Unfortunately, for full flexibility, we'd probably have to introduce some sort
of member conversion function for std.conv.tryTo to look for if we want this to
work with user-defined types without throwing (since calling the constructor or
casting like to does for user-defined types would act the same between to and
tryTo), but those don't generally throw a ConvException right now anyway (and
worse case, we can make tryTo catch any ConvExceptions that they do throw). So,
at minimum, we can just convert them like we do with to, and then if we want to
expand on that, we can designate a function for user-defined types to define if
they want to be able to tell tryTo that a conversion failed without throwing.

Regardless, having tryTo will at minimum improve the situation for built-in
types in the cases where having a ConvException be thrown on failure is a
problem.

--


More information about the Digitalmars-d-bugs mailing list