PRo*_*eau -2 c++ numeric-limits
假设头文件中有一个您无法控制的声明,其声明如下:
static const uint16 MaxValue = 0xffff; // the type could be anything, static or not
Run Code Online (Sandbox Code Playgroud)
在包含上述内容的文件中,您有如下代码:
int some_function(uint16 n) {
if (n > MaxValue) {
n = MaxValue;
}
do_something(n);
...
}
Run Code Online (Sandbox Code Playgroud)
编译器会警告 if 语句始终为 false,因为n不能大于 0xffff。
一种方法可能是删除代码。但是,如果后来有人想将 的值更改MaxValue为更低的值,那么您就引入了一个错误。
两个问题:
MaxValue是 0xffff)并包含代码(当MaxValue不是 0xffff 时)?MaxValue等于类型可以容纳的限制,是否有一种可移植的技术可用于识别类型的最大值,MaxValue如果稍后代码MaxValue发生更改,该技术将起作用?
limits.h或<limit>等常量USHRT_MAX,或未std::numeric_limits<uint16>显式使用的事件。std:numeric_limits<MaxValue> 可以使用类似的东西吗?typeid 结果是 type_info const & 而不是变量的类型,请使用
std::numeric_limits<decltype(variable)>::max()
Run Code Online (Sandbox Code Playgroud)
反而。