限制 C++ 中值类型的范围
假设我有一个 LimitedValue 类,它保存一个值,并在 int 类型min"和max"上参数化.您可以将它用作保存只能在特定范围内的值的容器.你可以这样使用它:
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 );
这样 'someTrigFunction' 就知道它保证提供一个有效的输入(如果参数无效,构造函数会抛出异常).
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?
推荐答案
你可以使用模板来做到这一点――试试这样的:
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
};
相关文章