在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 的值更改为更低的值,那么您刚刚引入了一个错误。

两个问题:

试试这个:

std:numeric_limits<decltype(n)>::max()

typeid 导致 type_info const & 而不是变量类型,使用

std::numeric_limits<decltype(variable)>::max()

相反。