|
Boost : |
From: Márcio Gil (marciomgil_at_[hidden])
Date: 2007-12-15 17:53:49
Hello,
I suggest this add on lexical_cast library: a lexical_cast_def function,
which work's like the AnsiString's ToIntDef method (from Borland VCL).
Reason: the use of a lexical_cast without a try ... catch block, if the
source is not guaranteed to be safe. Example:
string source;
int x = lexical_cast_def<int>( source, 0 );
In opposite of:
string source;
int x;
try
{
x = lexical_cast<int>( source );
}
catch(...)
{
x = 0;
}
Soon I can write this function in my project:
template<typename Target, typename Source>
Target lexical_cast_def(Source arg, Target def)
{
Target result;
try
{
result = lexical_cast<Target>(Source);
}
catch (..)
{
result = def;
}
return result;
}
Otherwise we can post in the library this simplest and fastest function:
template<typename Target, typename Source>
Target lexical_cast_def(Source arg, Target def)
{
detail::lexical_stream<Target, Source> interpreter;
Target result;
if(!(interpreter << arg && interpreter >> result))
return def;
return result;
}
And the call-by-const reference version.
Thanks,
Marcio Gil.
P.S.: This is my first post in this list, soon excuse my bad English, I
don't speak English, is that used only for reading.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk