Boost logo

Boost :

From: Jeff Garland (jeff_at_[hidden])
Date: 2003-10-05 11:08:44


On Sat, 4 Oct 2003 14:41:19 -0400, Edward Diener wrote
> In responding to Mr. Gregor's post about tribool, an idea has
> crossed my mind which has occurred a few times before. Some other
> languages are able to create native types which are subsets of all
> values of a given built-in type. It seems as if a generic template
> mechanism ( or two ) should be able to do this. As an example, for
> C++'s 'int' type I would like to create a type which holds 'ints'
> between certain values, let's say 1 and 100 and rejects assignments
> outside this range, perhaps throwing an exception if one is
> attempted. I would think that template magic would be able to do
> this for any given built-in integer type, and maybe for any type

In the date_time library I use a template called constrained_value to do this.
In several places I wanted to ensure that construction from a raw type was
within a valid range so I wouldn't need to check internally. As an example,
in the date part of the library to ensure that the constructed range of a year
is between 1400 and 10000 I have the following:
   //from gregorian/greg_year.hpp

   #include "boost/date_time/constrained_value.hpp"

  //! Exception type for gregorian year out of range
  struct bad_year : public std::out_of_range
  {
    bad_year() :
      std::out_of_range(std::string("Year is out of valid range: 1400..10000"))
    {}
  };
  //! Policy class that declares error handling gregorian year type
  typedef CV::simple_exception_policy<unsigned short, 1400, 10000, bad_year>
greg_year_policies;

  //! Generated representation for gregorian year
  typedef CV::constrained_value<greg_year_policies> greg_year_rep;

The implementation here is limited in that it doesn't provide all the
operators and other functions, but it is an example of what you are talking
about. The way this is implemented allows the user to define different error
handling strategies as the constrained_value calls an on_error function on the
policy class when the value is set out of range.

Jeff


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