Boost logo

Boost :

From: Robert Kawulak (tigrisek_at_[hidden])
Date: 2007-08-20 13:35:19


Hi all,

At last I've managed to find some time to polish the Constrained Value library
(former Constrained Types library) and want to share it to hear any opinions and
suggestions. If all goes OK, I'll request a formal review when the library is
completed. To remind what this library is about, an excerpt from the motivation
section of documentation is attached at the bottom of this message.

As for now, the implementation is complete, documentation is almost ready, tests
and examples have to be finished.

The code and documentation can be downloaded here:
http://rk.go.pl/f/constrained_value.zip
The documentation is also available online here:
http://rk.go.pl/r/constrained_value

Any feedback is very welcome!

Best regards,
Robert Kawulak

FROM THE MOTIVATION SECTION OF DOCUMENTATION:

The Boost Constrained Value library contains class templates useful for creating
constrained objects. The simplest example of a constrained object is hour. The
only valid values for an hour within a day are integers from the range [0, 23].
There's no C++ type which exactly matches this set of valid values, so a larger
integral type (e.g. int) must be used to represent hours. But this can lead to
errors -- for instance, one may accidentally assign an invalid value, say 26, to
a variable holding an hour. The Boost Constrained Value library provides a
mechanism protecting against such mistakes:

bounded_int<int, 0, 23>::type hour;
hour = 20; // OK
hour = 26; // error -- throws an exception

Another feature of the library is the ability to specify what happens in case of
assignment of an invalid value. For instance, an exception may be thrown as in
the example above, or the value may be adjusted to meet the constraint
criterions:

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 constrained objects that hold a value
belonging to a specified range (i.e., bounded objects). Virtually any constraint
can be imposed using appropriate predicate:

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

// and the usage is as simple as:
constrained<int, is_even>::type even_int;
even_int = 2; // OK
even_int++; // error -- throws an exception


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk