Suggestion to lexical_cast library

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.

Márcio Gil wrote:
I suggest this add on lexical_cast library: a lexical_cast_def function,
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; }
This wouldn't only be useful to lexical_cast. What about a more generic utility? template<typename F, typename T> T call_default(F f, T t) { try { return f(); } catch { return t; } } Unfortunately, this requires usage of function objects, and lambdas are not so popular. Maybe one can do it with actual C++ expressions using macros.
participants (2)
-
Mathias Gaunard
-
Márcio Gil