Easy casting with boost::lexical_cast and std::to_string

If you haven’t used boost, you need to start using it. Actually, if you’re not using the standard C++ library or STL, you should learn how to use most of that first. Since starting my new job at D4D Technologies, I have been using a lot of boost. One of the most useful is boost::lexical_cast<>().

Basically it allows you to cast from one data type to another by specifying a specific data type to cast to. The old way of casting from a float to a string, for example, is to use string stream. This requires about 3 lines of code and it’s messy. Alternatively you could use the nasty C-style sprintf(), which has it’s own problems.

The new way is to just do this:

The newest C++11 standard has something of value that is similar, but there are a lot of variations.
The difference is that boost requires a datatype, whereas the C++ library functions do not.
One issue I have with them is that they’re all named differently and you have to look them up. But they work like this:

These are all of the new C++ 11 converter functions, to and from string.


Leave a Reply

You must be logged in to post a comment.