
----Original Message---- From: Stephen Gross [mailto:sgross@darwin.epbi.cwru.edu] Sent: 14 September 2005 18:19 To: boost@lists.boost.org Subject: Re: [boost] Checked Integral Class
I've written a template class to hold a range of valid integral values. My intent was to mimic Ada's ability to define a type like this:
type SmallInt is range -10 .. 10;
One can then declare objects of this type and any subsequent assignment that violated this range constraint woud throw an exception.
I have built a C++ template class that does the same thing:
template<typename T, T min, T max> struct CheckedIntegralValue
To define a type that can hold the same range as the example above:
typedef CheckedIntegralValue<int, -10, 10> SmallIntType;
SmallIntType i = -10;//OK SmallIntType i2 = -100;//Will throw an exception at run-time for value out-of-range
I won't include the whole thing here, but I can do so if there is enough interest. I have defined most of the operators one needs to use this type just as one would use a 'normal' integer.
Would anyone be interested in something like this in the Boost libraries?
Since the assignment check is done at runtime (as it has to be), why make the range restriction at compile time? Isn't it more useful to have a class that works more like this:
=== CODE === CheckedIntegralValue x; x.setLowerLimit(-5); x.setUpperLimit(1000); x = 10; x = 9000; // Fails at runtime ===========
Does this make sense?
= sizeof(int). Structures which fit in an machine word can more easily be
Because: a) You often have a conceptual type whose limits are known at compile time. Different conceptual types in your program will often have different limits, so you get better typesafety almost for free. b) If you carry the limits in the objects, sizeof(CheckedIntegralValue) >= 3*sizeof(int); if you make them compile time, sizeof(CheckedIntegralValue) passed in registers. c) By making the limits compile time constants, if you assign an in-range constant the optimizer can eliminate the test entirely. -- Martin Bonner Martin.Bonner@Pitechnology.com Pi Technology, Milton Hall, Ely Road, Milton, Cambridge, CB4 6WZ, ENGLAND Tel: +44 (0)1223 441434