Boost logo

Boost :

From: Brian Martin (brmartin_at_[hidden])
Date: 2004-04-01 10:33:00


Brian Martin wrote:
> I have a suggestion for a simple Boost feature - subranges.
> The big question is, do any of you think this is a useful enough feature?

Maciej Sobczak wrote:

>Yes, it is.
>What's more, the biggest gain (in my humble opinion, of course) is not
>the bare fact that you can have range checking at run-time, but that it
>is possible to provide range checking at *compile-time*, thus
>strengthening the type system.

There are some interesting ideas in your code. The current version of my subrange class does not trap potential compile time errors. Your technique of using template specialisation for this is a good idea but unfortunately the following gets past my (Borland) compiler:

range<0, 200> k4(500);

and it would be nice to catch this.

Also, I don't see how the following can ever be trapped by a compiler:

range<0, 100> i(4);

i = 98;



surely that is a runtime thing.

One possible idea for catching the first one is to redefine the template as follows:

template <long L, long U, long V>

class range
    long v_;


        static_assert<L <= V && V < U>();
        v_ = V;

I've tried this on a simple example and it seems to work. Unfortunately, what you pass to V has to be a constant expression. Thus this won't compile at all:

const long x = 2;

range<0, 10, x> my_range;

Even though x is in range and const. I suppose it's a const "variable". Drat.

Your class doesn't have the concept of a "base type". It's a template restricted to longs. Class subrange allows restriction of any type that supports the appropriate numerical operators (even classes - admittedly a bit dubious). This is similar to the Pascal facility where you can have subranges on any ordinal type (i.e. integral numerical, character or enumeration) e.g.

type LowerCaseChar = 'a'..'z';

type UpperCaseChar = 'A'..'Z';

type DaysOfTheWeek = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday); // equal to a C++ enum declaration

type WorkingDay = Monday..Friday; // For those who don't work weekends!

I know that C++ does implicit conversions from say char to int etc. e.g.

typedef range<'a', 'z'> lowercase_char;


typedef subrange<char, 'a', 'z'> lowercase_char;

is a bit more "self documenting". The specification of the base type char makes it clear we're storing characters and not longs.

I'll have another think about some of the compile time check issues.

Regards, Brian Martin
Unsubscribe & other changes: <>

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