Is boost::lexical_cast
redundant now that C++11 introduces stoi
, stof
and family, or is there any reason to still use it? (apart from not having a C++11 compiler) Do they provide exactly the same functionality?
boost::lexical_cast
sto*
have different names for different types)sto*
/to_string
are only in part, e.g. lexical_cast
can process thousands separators, while stoul
usually doesn't)boost::lexical_cast
gives you a uniform interface across types which is often very important in generic code.
In general, consistent interface across types for same functionality allows generic code better. For example, following can be used as generic parser from string tokens to std::tuple:
template<typename T>
void fill(T& item, const std::string& token){
item = boost::lexical_cast<T>(token)
}
template<int N, typename ...Ts>
void parse(std::integral_constant<int, N>, std::tuple<Ts...>& info, std::vector<std::string>& tokens) {
fill(std::get<N>(info), tokens[N]);
parse(std::integral_constant<int, N - 1>, info, tokens);
}
template<typename ...Ts>
void parse(std::integral_constant<int, 0>, std::tuple<Ts...>& info, std::vector<std::string>& tokens) {
fill(std::get<0>(info), tokens[0]);
}
Instead of tuple, I often use boost fusion struct to deserialize some tokenized strings directly into a struct in a generic way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With