Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

tom_int
PrevUpHomeNext

#include <boost/multiprecision/tommath.hpp>

namespace boost{ namespace multiprecision{

class tommath_int;

typedef number<tommath_int >         tom_int;

}} // namespaces

The tommath_int back-end is used via the typedef boost::multiprecision::tom_int. It acts as a thin wrapper around the libtommath tom_int to provide an integer type that is a drop-in replacement for the native C++ integer types, but with unlimited precision.

Things you should know when using this type:

  • Default constructed objects have the value zero (this is libtommath's default behavior).
  • Although tom_int is mostly a drop in replacement for the integer fundamental (built-in) types, it should be noted that it is a rather strange beast as it's a signed type that is not a 2's complement type. As a result the bitwise operations | & ^ will throw a std::runtime_error exception if either of the arguments is negative. Similarly the complement operator~ is deliberately not implemented for this type.
  • Formatted IO for this type does not support octal or hexadecimal notation for negative values, as a result performing formatted output on this type when the argument is negative and either of the flags std::ios_base::oct or std::ios_base::hex are set, will result in a std::runtime_error will be thrown.
  • Conversion from a string results in a std::runtime_error being thrown if the string can not be interpreted as a valid integer.
  • Division by zero results in a std::overflow_error being thrown.
Example:
#include <boost/multiprecision/tommath.hpp>
#include <iostream>

int main()
{
   boost::multiprecision::tom_int v = 1;

   // Do some arithmetic:
   for(unsigned i = 1; i <= 1000; ++i)
      v *= i;

   std::cout << v << std::endl; // prints 1000!
   std::cout << std::hex << v << std::endl; // prints 1000! in hex format

   try{
      std::cout << std::hex << -v << std::endl; // Ooops! can't print a negative value in hex format!
   }
   catch(const std::runtime_error& e)
   {
      std::cout << e.what() << std::endl;
   }

   try{
      // v is not a 2's complement type, bitwise operations are only supported
      // on positive values:
      v = -v & 2;
   }
   catch(const std::runtime_error& e)
   {
      std::cout << e.what() << std::endl;
   }

   return 0;
}

PrevUpHomeNext