nothrow function to tell if a string can be converted to a number?
Jonathan M Davis
jmdavisProg at gmx.com
Fri Sep 6 23:00:52 PDT 2013
On Friday, September 06, 2013 22:38:20 H. S. Teoh wrote:
> On Sat, Sep 07, 2013 at 12:38:58AM -0400, Jonathan M Davis wrote:
> > On Friday, September 06, 2013 21:15:44 Timothee Cour wrote:
> > > I'd like to have a function:
> > >
> > > @nothrow bool isNumberLitteral(string a);
> > > unittest{
> > > assert(isNumberLitteral("1.2"));
> > > assert(!isNumberLitteral("a1.2"));
> > > assert(!isNumberLitteral("a.b"));
> > > }
> > >
> > > I want it nothrow for efficiency (I'm using it intensively), and
> > > try/catch as below has significant runtime overhead (esp when the
> >
> > > exception is caught):
> > You could try std.string.isNumeric.
> >
> > But it's true that it would be nice to have some sort of counterpart
> > to std.conv.to which checked whether a conversion was possible or
> > which returned its argument via an out parameter and returned whether
> > it succeeded or not (or something similar) for cases where you need to
> > avoid throwing.
> >
> > http://d.puremagic.com/issues/show_bug.cgi?id=6840
> > http://d.puremagic.com/issues/show_bug.cgi?id=6843
>
> [...]
>
> I like the idea of maybeTo!(). But I'm not sure if it's possible to
> guarantee performance -- conversion to user-defined types, for example,
> may involving a ctor that might throw. If so, it's impossible to
> implement maybeTo!() without using try/catch, so the performance hit
> will still be there.
>
> But at least, it will buy us performance when basic types are used.
If need be, we could go the route of creating a new function which std.conv.to
looks for in addition to the cast operator where that function does a
conversion without throwing and returns false when it fails or returns a
Nullable or something along those lines so that std.conv.to can take advantage
of it. And if the type doesn't implement that function, then either it won't
work with the version of to which doesn't throw, or that version of to will
use a try-catch (though I'd be inclined to make it require that function in
order to avoid invisible performance hits).
But I really don't like the idea of maybeTo as Bearophile describes it (as a
wrapper around to which catches the exception). I think that we really need a
version of to which takes care of this (and it could be called maybeTo if we
wanted, but it needs to not doing any wrapping).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list