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++ 中值类型的范围


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01