在C++中,如何通过变量名来表示一个类型的最大可能值?
In C++, how to express the largest possible value of a type via its variable name?
假设头文件中有一个您无法控制的声明,声明如下:
static const uint16 MaxValue = 0xffff; // the type could be anything, static or not
在包含上述内容的文件中,您有如下代码:
int some_function(uint16 n) {
if (n > MaxValue) {
n = MaxValue;
}
do_something(n);
...
}
编译器会警告 if 语句总是错误的,因为 n
不能大于 0xffff。
一种方法可能是删除代码。但是,如果稍后有人想将 MaxValue
的值更改为更低的值,那么您刚刚引入了一个错误。
两个问题:
- 是否有任何 C++ 模板或技术可用于确保代码在不需要时被删除(因为
MaxValue
是 0xfff)和包含(当 MaxValue
不是 0xffff 时)?
- 假设您想明确地编写一个额外的检查来查看
MaxValue
是否等于该类型可以容纳的限制,是否有一种可移植的技术可用于识别 [= 类型的最大值13=] 如果稍后更改 MaxValue
的代码,它会起作用吗?
- 含义:如何通过其变量名称推断类型的最大值?
- 我宁愿不使用像
USHRT_MAX
这样的 limits.h
或 <limit>
常量,或者不明确使用 std::numeric_limits<uint16>
的事件。
- 可以使用
std:numeric_limits<MaxValue>
之类的东西吗?
试试这个:
std:numeric_limits<decltype(n)>::max()
typeid 导致 type_info const & 而不是变量类型,使用
std::numeric_limits<decltype(variable)>::max()
相反。
假设头文件中有一个您无法控制的声明,声明如下:
static const uint16 MaxValue = 0xffff; // the type could be anything, static or not
在包含上述内容的文件中,您有如下代码:
int some_function(uint16 n) {
if (n > MaxValue) {
n = MaxValue;
}
do_something(n);
...
}
编译器会警告 if 语句总是错误的,因为 n
不能大于 0xffff。
一种方法可能是删除代码。但是,如果稍后有人想将 MaxValue
的值更改为更低的值,那么您刚刚引入了一个错误。
两个问题:
- 是否有任何 C++ 模板或技术可用于确保代码在不需要时被删除(因为
MaxValue
是 0xfff)和包含(当MaxValue
不是 0xffff 时)? - 假设您想明确地编写一个额外的检查来查看
MaxValue
是否等于该类型可以容纳的限制,是否有一种可移植的技术可用于识别 [= 类型的最大值13=] 如果稍后更改MaxValue
的代码,它会起作用吗?- 含义:如何通过其变量名称推断类型的最大值?
- 我宁愿不使用像
USHRT_MAX
这样的limits.h
或<limit>
常量,或者不明确使用std::numeric_limits<uint16>
的事件。 - 可以使用
std:numeric_limits<MaxValue>
之类的东西吗?
- 我宁愿不使用像
- 含义:如何通过其变量名称推断类型的最大值?
试试这个:
std:numeric_limits<decltype(n)>::max()
typeid 导致 type_info const & 而不是变量类型,使用
std::numeric_limits<decltype(variable)>::max()
相反。