Reputation: 11
i am using lexical cast in a function for three different variables. Now if a bad_lexical_cast exception occurs i have to set default values respective to each variable. now how to find from which statement the exception is thrown?
Upvotes: 0
Views: 252
Reputation: 136296
You can assign the default values first and then wrap each boost::lexical_cast
into a try-catch
block.
Or, better, extract a function that does it for you:
#include <boost/lexical_cast.hpp>
#include <iostream>
template<class T, class S>
T lexical_cast_or_default(S s, T default_value) noexcept {
T value;
return boost::conversion::try_lexical_convert(s, value)
? value
: default_value
;
}
int main() {
double a = lexical_cast_or_default("abc", 3.14);
double b = lexical_cast_or_default("123", 3.14);
int c = lexical_cast_or_default<int>("456", 3.14);
std::cout << a << '\n';
std::cout << b << '\n';
std::cout << c << '\n';
}
Outputs:
3.14
123
456
Upvotes: 2