user23434 user23434 - 1 year ago 87
C++ Question

Limiting range of value types in C++

Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:

LimitedValue< float, 0, 360 > someAngle( 45.0 );
someTrigFunction( someAngle );

so that 'someTrigFunction' knows that it is guaranteed to be supplied a valid input (The constructor would throw an exception if the parameter is invalid).

Copy-construction and assignment are limited to exactly equal types, though. I'd like to be able to do:

LimitedValue< float, 0, 90 > smallAngle( 45.0 );
LimitedValue< float, 0, 360 > anyAngle( smallAngle );

and have that operation checked at compile-time, so this next example gives an error:

LimitedValue< float, -90, 0 > negativeAngle( -45.0 );
LimitedValue< float, 0, 360 > postiveAngle( negativeAngle ); // ERROR!

Is this possible? Is there some practical way of doing this, or any examples out there which approach this?

Answer Source

You can do this using templates -- try something like this:

template< typename T, int min, int max >class LimitedValue {
   template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other )
   static_assert( min <= min2, "Parameter minimum must be >= this minimum" );
   static_assert( max >= max2, "Parameter maximum must be <= this maximum" );

   // logic
// rest of code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download