Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min and Max values for integer variable at compile time in C++

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
like image 368
Harvey Avatar asked Nov 28 '22 23:11

Harvey


1 Answers

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

like image 92
Naveen Avatar answered Dec 05 '22 16:12

Naveen