Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is boost::lexical_cast redundant with c++11 stoi, stof and family?

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?

like image 918
Ela782 Avatar asked May 10 '14 14:05

Ela782


2 Answers

boost::lexical_cast

  • handles more kinds of conversion, including iterator pairs, arrays, C strings, etc.
  • offers the same generic interface (sto* have different names for different types)
  • is locale-sensitive (sto*/to_string are only in part, e.g. lexical_cast can process thousands separators, while stoul usually doesn't)
like image 78
Cubbi Avatar answered Oct 27 '22 02:10

Cubbi


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.

like image 20
OOO Avatar answered Oct 27 '22 01:10

OOO