C ++中值类型的限制范围 [英] Limiting range of value types in C++

查看:52
本文介绍了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
};

这篇关于C ++中值类型的限制范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆