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

This is an old version of boost. Click here for the latest version's documentation home page.

Compile-Time Integral Type Limits

The C++ Standard Library <limits> header supplies a class template numeric_limits<> with specializations for each fundamental type.

For integer types, the interesting members of std::numeric_limits<> are:

   static const bool is_specialized; // will be true for integers
   static T min() throw();
   static T max() throw();
   static const int digits;     // for integers, # value bits
   static const int digits10;     
   static const bool is_signed;
   static const bool is_integer; // will be true for integers
For many uses, these are sufficient. But min() and max() are problematical because they are not constant expressions (std::5.19), yet some usages require constant expressions.

The template class integer_traits addresses this problem.

Header integer_traits.hpp Synopsis

namespace boost {
  template<class T>
  class integer_traits : public std::numeric_limits<T>
  {
    static const bool is_integral = false;
  };

  // specializations for all integral types
}

Description

Template class integer_traits is derived from std::numeric_limits. In general, it adds the single bool member is_integral with the compile-time constant value false. However, for all integral types T (std::3.9.1/7 [basic.fundamental]), there are specializations provided with the following compile-time constants defined:

membertypevalue
is_integralbooltrue
const_minTequivalent to std::numeric_limits<T>::min()
const_maxTequivalent to std::numeric_limits<T>::max()

Note: A flag is_integral is provided, because a user-defined integer class should specialize std::numeric_limits<>::is_integer = true, nonetheless compile-time constants const_min and const_max cannot be provided for that user-defined class.

Test Program

The program integer_traits_test.cpp exercises the integer_traits class.

Acknowledgements

Beman Dawes, Ed Brey, Steve Cleary, and Nathan Myers discussed the integer traits idea on the boost mailing list in August 1999.
Jens Maurer, 2000-02-20