I use the boost lexical_cast library for parsing text data into numeric values quite often. In several situations however, I only need to check if values are numeric; I don't actually need or use the conversion.
So, I was thinking about writing a simple function to test if a string is a double:
template<typename T>
bool is_double(const T& s)
{
try
{
boost::lexical_cast<double>(s);
return true;
}
catch (...)
{
return false;
}
}
My question is, are there any optimizing compilers that would drop out the lexical_cast here since I never actually use the value?
Is there a better technique to use the lexical_cast library to perform input checking?
You can now use boost::conversion::try_lexical_convert
now defined in the header boost/lexical_cast/try_lexical_convert.hpp
(if you only want try_lexical_convert
). Like so:
double temp;
std::string convert{"abcdef"};
assert(boost::conversion::try_lexical_convert<double>(convert, temp) != false);