views:

479

answers:

4

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;
// 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
+8  A: 

Use std::numeric_limits, it is there for exactly this type of requirement. You can take a look at this example for the usage.

Naveen
AFAIK, those are not *compile-time*, though (if OP himself realizes what exactly he wants).
UncleBens
Not compile-time, but fairly close to it if optimisations are enabled.
RaphaelSP
RaphaelSP: if compile-time is actually required, such as for a template parameter or enumerator, then it doesn't matter what optimizations are enabled---either the expression is or it isn't. Compare to constexprs in C++0x.
Roger Pate
Good point. I just translated "compile-time" to "fast" (given the code snippet does not do sensible use of the "compile-time" bit).
RaphaelSP
+10  A: 

Check out boost integer_traits.

moonshadow
+2  A: 

See this question http://stackoverflow.com/questions/1855459/maximum-value-of-int - you can also use "min" in the places where the answers used "max"

anon
A: 

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.

seh
Wrong. It is not compile time.
Alexey Malistov
True, and the client code above could not distinguish evaluation at run time from compile time. All the implementations for `numeric_limits` I've seen are functions exposing constants defined at compile-time, but I don't think it was a mistake that the standard mandates those values be exposed through functions as opposed to constant member values -- in particular, to accommodate the floating point types or some other non-ICE.
seh