nothrow function to tell if a string can be converted to a number?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Sep 6 22:38:20 PDT 2013


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.


T

-- 
It is of the new things that men tire --- of fashions and proposals and
improvements and change. It is the old things that startle and
intoxicate. It is the old things that are young. -- G.K. Chesterton


More information about the Digitalmars-d-learn mailing list