Home > Frameworks > boost::conversion

boost::conversion

To stay clear from the old fashioned and highly unsafe C casting, the C++ offers a small array of specialized casting options, like static_cast, dynamic_cast, etc.  The Boost Conversion framework brings more on the table.

polymorphic_cast<T>()   —  boost/cast.hpp

The simplest one, it wraps a dynamic_cast into a NULL check (and throws a std::bad_cast if it fails).  That is, if you intend your casting to always succeed, you should be calling polymorphic_cast for safety instead of dynamic_cast, unless you want to do your own error handling.

polymorphic_downcast<T>()   —  boost/cast.hpp

This one is almost identical to polymorphic_cast, but instead of checking for NULL, it checks for equivalency of pointer addresses using a dynamic_cast (only in NDBEUG mode) and assert if it fails.  Then it returns a static_cast.  Looks like the difference with this one is that it is optimized in non-debug builds, at the price of losing error checks.

lexical_cast<T>()   —  boost/lexical_cast.hpp

This one offers a safe and very flexible way to convert between strings and numeric values.  Instead of using a clunky combination of atoi() and sprintf(), lexical_cast offers simple translation from one another.  It supports plain char strings, STL strings (and wstrings), etc.  In case a casting is not possible, it will throw a bad_lexical_cast exception.

I was already using a lot of what is called an assert_cast<>() which essentially the same as the polymorphic_cast, except with an assert.  It really is handy.

The new one I learned and will put to good use right away is lexical_cast.  I can’t believe I lived so long using atoi / sprintf combinations for so long.

 

 

Categories: Frameworks
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment