Claudiu Claudiu - 2 months ago 77
C++ Question

What's the difference between std::to_string, boost::to_string, and boost::lexical_cast<std::string>?

What's the purpose of

boost::to_string
(found in
boost/exception/to_string.hpp
) and how does it differ from
boost::lexical_cast<std::string>
and
std::to_string
?

Answer

std::to_string, available since C++11, works on fundamental numeric types specifically. It also has a std::to_wstring variant.

It is designed to produce the same results that std::sprintf would.

You may choose this form to avoid dependencies on external libraries/headers.


boost::lexical_cast<std::string> works on any type that can be inserted into a std::ostream, including types from other libraries or your own code.

Optimized specializations exist for common types, with the generic form resembling:

template< typename OutType, typename InType >
OutType lexical_cast( const InType & input ) 
{
    std::stringstream temp_stream;
    temp_stream << input;

    OutType output;
    temp_stream >> output;
    return output;
}

You may choose this form to leverage greater flexibility of input types in generic functions, or to produce a std::string from a type that you know isn't a fundamental numeric type.


boost::to_string isn't directly documented, and seems to be for internal use primarily. Its functionality behaves like lexical_cast<std::string>, not std::to_string.