Boost logo

Boost :

From: Brian Martin (brmartin_at_[hidden])
Date: 2004-03-31 08:01:55

I have a suggestion for a simple Boost feature - subranges.

For those of you who may not know, subranges are a Pascal idea. Using
un-restricted numeric types such as ints, shorts and floating point types is
somewhat dangerous. For example, if you write a function that, given a date,
returns the number of the day in the year that date falls on, what type do
you return? Most C/C++ programmers would automatically use an int but ints
can be negative and -1 as a day of the year is meaningless. So use unsigned
types. But then 0 is invalid, as is any value above 365. Subranges to the
rescue... In pascal one would write

type DayOfYear = 1..365;

function NthDayOfYear(const d : Date) : DayOfYear;

The type statement declares a new data type that is restricted to the range
1 to 365 and this is used as the return type of the function. If
NthDayOfYear has a fault that sometimes generates a value outside this
range, you'll get a runtime error. The idea is to have range checking
switched on during development, but to switch if off for release code for
efficiency reasons, something that all good pascal compilers can do.

My own personal experience having used pascal type languages with this
feature is that it's very, very useful indeed. On a number of projects,
subranges have illuminated obscure bugs in my code that I might otherwise
have missed. After having switched to C++ from Pascal, I soon found myself
missing subranges so I wrote a class template that emulates them:

template <typename T, T min, T max> class subrange;

This would contain the usual operators/constructors etc. that I've omitted
for shortness. The above example would now become in C++:

typedef subrange<int, 1, 365> day_of_year;
day_of_year NthDayOfYear(const Date& d);

The class is very simple - all it does is store a value and then checks to
make sure it's always in the range min to max when you assign variables of
type T to it, do arithmetic and so on and throws an exception if the new value is
out of range. A preprocessor symbol is used to switch this range checking on
or off as required so that you can release code without the checking

The big question is, do any of you think this is a useful enough feature?

Regards, Brian

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