...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
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 builtin // integal type: // static const T const_min = implementationdefined; static const T const_max = implementationdefined; }; }
Template class integer_traits
is derived from std::numeric_limits
.
The primary specialization adds the single bool
member
is_integral
with the compiletime constant value false
.
However, for all integral types T
(std::3.9.1/7 [basic.fundamental]),
there are specializations provided with the following compiletime constants
defined:
member 
type 
value 


bool 



equivalent to 


equivalent to 
Note: The is_integral flag is provided, because a userdefined
integer class should specialize std::numeric_limits<>::is_integer
= true
, while compiletime constants const_min
and const_max
are not provided for that userdefined 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.