一千萬個為什麽

搜索

整數變量在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();//Same as e = -128;//Using the typename directly

最佳答案

使用std :: numeric_limits,它恰好就是這種類型的需求。您可以查看此示例用法。

轉載註明原文: 整數變量在C ++編譯時的最小值和最大值