[英]Min and Max values for integer variable at compile time in C++
有一种简单,干净的方法可以在编译时确定某些变量(此时是未知的)整数变量或类型的最大值和最小值吗? 使用模板?
例如:
// Somewhere in a large project is:
typedef unsigned long XType;
typedef char YType;
// ...
// Somewhere else
XType a;
YType b;
LONGLONG c,d,e,f;
c = MinOfType(a); // Same as c = 0;
d = MaxOfType(a); // Same as d = 0xffffffff;
e = MinOfType(b); // Same as e = -128;
f = MaxOfType(b); // Same as f = 127;
// Also would be nice
e = MinOfType(YType); // Same as e = -128; // Using the typename directly
// Or perhaps
e = MinOfType<YType>(); // Same as e = -128; // Using the typename directly
使用std :: numeric_limits,它就是这种类型的要求。 您可以查看此示例以了解用法。
看到这个问题int的最大值 - 你也可以在答案使用“max”的地方使用“min”
如果您可以访问c ++ 11,则可以使用decltype
和std::numeric_limits
的组合。 重写示例代码如下所示:
#include <limits>
typedef unsigned long XType;
typedef char YType;
XType a;
YType b;
LONGLONG c,d,e,f;
c = std::numeric_limits< decltype(a) >::min(); // Same as c = 0;
d = std::numeric_limits< decltype(a) >::max(); // Same as d = 0xffffffff;
e = std::numeric_limits< decltype(b) >::min(); // Same as e = -128;
f = std::numeric_limits< decltype(b) >::max(); // Same as f = 127;
e = std::numeric_limits< YType >::min(); // Same as e = -128; // Using the typename directly
decltype
将从表达式中提取类型,在这种情况下阻止变量类型,并允许您在其他期望类型(如模板)的位置使用它。 这一切都发生在编译时,以便您可以将其分配给constexpr
。
constexpr decltype(a) g = std::numeric_limits< decltype(a) >::min();
这里g
与a
类型相同,值为0,并且都在编译时确定。
包含标题<limits>
以到达模板类std::numeric_limits
。 变量的数字类型用于查找该模板类的特化,该模板类将通过函数max()
提供最大值,并通过min()
提供min()
,此外还有该类型的其他几个方面。
请注意,对于整数和浮点类型, 最小值的解释是不同的。 对于前者,它是有符号类型的最负值,对于无符号类型是零,但对于后者,它是最小的可表示值,非常接近于零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.