Limiting range of value types in C++(限制 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++ 中值类型的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:限制 C++ 中值类型的范围


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07