Boost logo

Boost :

From: Edward Diener (eddielee_at_[hidden])
Date: 2003-10-05 11:46:40

Jeff Garland wrote:
> 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")) {}
> };

Unfortunately you are hardcoding the range in your exception rather than
getting it from your policy class's template parameters somehow.

> //! Policy class that declares error handling gregorian year type
> typedef CV::simple_exception_policy<unsigned short, 1400, 10000,
> bad_year> greg_year_policies;

Yes, this is the sort of thing about which I was thinking. I will look at

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

Yes, understood.

> 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.

Sounds good, I will look at your code for your policy. Thanks !

Boost list run by bdawes at, gregod at, cpdaniel at, john at