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 the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Integer Traits

Motivation
Synopsis
Description
Test Program
Acknowledgements

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 integer types.
static T min() throw();                // Smallest representable value.
static T max() throw();                // Largest representable value.
static const int digits;               // For integers, the number of value bits.
static const int digits10;             // The number of base 10 digits that can be represented.
static const bool is_signed;           // True if the type is signed.
static const bool is_integer;          // Will be true for all integer types.

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.

namespace boost {
  template<class T>
  class integer_traits : public std::numeric_limits<T>
  {
  public:
     static const bool is_integral = false;
     //
     // These members are defined only if T is a built-in
     // integal type:
     //
     static const T const_min = implementation-defined;
     static const T const_max = implementation-defined;
  };
}

Template class integer_traits is derived from std::numeric_limits. The primary specialization 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:

member

type

value

is_integral

bool

true

const_min

T

equivalent to std::numeric_limits<T>::min()

const_max

T

equivalent to std::numeric_limits<T>::max()

Note: The is_integral flag is provided, because a user-defined integer class should specialize std::numeric_limits<>::is_integer = true, while compile-time constants const_min and const_max are not provided for that user-defined class, unless boost::integer_traits is also specialized.

The program integer_traits_test.cpp exercises the integer_traits class.

Beman Dawes, Ed Brey, Steve Cleary, and Nathan Myers discussed the integer traits idea on the boost mailing list in August 1999.


PrevUpHomeNext