Is there a simple, clean way of determining at compile time the max and min values for a variable of some (otherwise unknown at the moment) integer variable or type? Using templates?
For example:
// 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;
// Als开发者_运维知识库o 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
Use std::numeric_limits, it is there for exactly this type of requirement. You can take a look at this example for the usage.
Check out boost integer_traits.
See this question maximum value of int - you can also use "min" in the places where the answers used "max"
If you have access to c++11, you can use a combination of decltype
and std::numeric_limits
. Rewriting your sample code would look like this:
#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
will pull the type from an expression, snagging the variable type in this case, and let you use it in other places that expect a type such as a template. And it all happens at compile time such that you could assign it to a constexpr
.
constexpr decltype(a) g = std::numeric_limits< decltype(a) >::min();
Here g
would be of the same type as a
, would have the value 0, and all be determined at compile time.
Include header <limits>
to reach template class std::numeric_limits
. The numeric type of your variable is used to find a specialization of that template class that will provide the maximum value via function max()
and the minimum value via min()
, in addition to several other facets of the type.
Note that the interpretation for minimum is different for integral and floating point types. For the former, it's the most negative value for a signed type, and zero for an unsigned type, but for the latter, it's the smallest representable value, which is very close to zero.
精彩评论