www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 17896] New: Alternate version of std.conv.to which returns


          Issue ID: 17896
           Summary: Alternate version of std.conv.to which returns
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: phobos
          Assignee: nobody puremagic.com
          Reporter: issues.dlang 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;
    i = to!int(str);

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);

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.


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

Oct 11 2017