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

Dmitry Olshansky dmitry.olsh at gmail.com
Sat Sep 7 03:57:03 PDT 2013


07-Sep-2013 09:38, H. S. Teoh пишет:
> 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.

As it's a template it could be inferred as nothrow for basic types.

I've been constantly looking for something like:

bool tryTo(T)(ref T dest, ...<same args as in to>)

That either parses successfully or returns false and leaves dest unaffected.
>
> But at least, it will buy us performance when basic types are used.
>
>
> T
>


-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list