Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) boost::numeric_cast

 

boost::numeric_cast is a safe number conversion function that throws an exception if the conversion cannot succeed.

 

In the example below, the highest possible int is converted to a short. Because this will fail, boost::numeric_cast throws an exception.

 

#include <boost/static_assert.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/limits.hpp>

int main()
{
  //Assume that short occupies less storage in memory than int.
  BOOST_STATIC_ASSERT(sizeof(short) < sizeof(int));

  //Obtain the highest integer value.
  const int x = boost::numeric::bounds<int>::highest();

  //Try to store the highest integer value as a short.
  //This will throw boost::numeric::positive_overflow,
  //because a short occupies to few memory to store such
  //a large number.
  const short y = boost::numeric_cast<short>(x);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict