Boost C++ Libraries Home Libraries People FAQ More


The Boost Constrained Value library

Robert Kawulak

Distributed under the Boost Software License, Version 1.0 (see accompanying file LICENSE_1_0.txt or copy at

Table of Contents

Basic definitions
Implementation notes
Revision history
Simple constrained objects
Changing constraints at runtime
Custom error policies
Bounded objects
Bounded objects with open ranges
Compile-time fixed bounds
Other error policies for bounded objects
Using constrained objects in debug mode only
Bounded-length string
Wrapping iterator
Object remembering its past extreme values
Why bounded objects don't protect against arithmetic overflows?
Why C++'s floating point types shouldn't be used with bounded objects?
Why wrap and clip policies don't allow the bounds to be excluded?
Why there's no automatic deduction of the underlying type for integral bounded objects?
[Important] Important

This is not an official Boost library yet. It is prepared for a formal review and therefore contains information stating it is a part of Boost, but it has not yet been formally reviewed nor accepted.

The Boost Constrained Value library contains class templates useful for creating constrained objects. A simple example is an object representing an hour of a day, for which only integers from the range [0, 23] are valid values:

bounded_int<int, 0, 23>::type hour;
hour = 20; // OK
hour = 26; // exception!

Behavior in case of assignment of an invalid value can be customized. For instance, instead of throwing an exception as in the example above, the value may be adjusted to meet the constraint:

wrapping_int<int, 0, 255>::type buffer_index;
buffer_index = 257; // OK: adjusts the value to fit in the range by wrapping it
assert( buffer_index == 1 );

The library doesn't focus only on bounded objects as in the examples above -- virtually any constraint can be imposed by using a predicate:

// constraint (a predicate)
struct is_odd {
    bool operator () (int i) const
    { return (i % 2) != 0; }

// and the usage is as simple as:
constrained<int, is_odd> odd_int = 1;
odd_int += 2; // OK
++odd_int; // exception!

The library has a policy-based design to allow for flexibility in defining constraints and behavior in case of assignment of invalid values. Policies may be configured at compile-time for maximum efficiency or may be changeable at runtime if such dynamic functionality is needed.

Last revised: November 30, 2008 at GMT