patterncppMinor
Version of lexical_cast that doesn't use exceptions
Viewed 0 times
lexical_castexceptionsversiondoesnthatuse
Problem
I love
I have implemented a version and it seems to work but I want to share it here to hopefully find any defects and/or simply find improvements.
Here is the code on Coliru where I've been testing.
boost::lexical_cast but its usage of exceptions there is not preferred in most situations I use it.I have implemented a version and it seems to work but I want to share it here to hopefully find any defects and/or simply find improvements.
template
T1 lexical_cast(T2 const& value, T1 const& defaultValue = T1{})
{
T1 convertedValue;
std::stringstream ss;
if (!(ss > convertedValue))
{
return defaultValue;
}
return convertedValue;
}Here is the code on Coliru where I've been testing.
Solution
I know I am quite late, but
try_lexical_convert() can be utilized:using boost::conversion::try_lexical_convert;
if(try_lexical_convert(source, target)) {
// ...
}Code Snippets
using boost::conversion::try_lexical_convert;
if(try_lexical_convert(source, target)) {
// ...
}Context
StackExchange Code Review Q#79682, answer score: 2
Revisions (0)
No revisions yet.