【发布时间】:2010-12-26 11:12:51
【问题描述】:
是否有一种简单、干净的方法可以在编译时确定某个(否则目前未知)整数变量或类型的变量的最大值和最小值?使用模板?
例如:
// 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
【问题讨论】:
-
编译时无法知道变量的值,但常量可以。
-
上述代码中不需要变量的“值”。但是,在我的示例中,变量的类型不是在编译时已知的。这些变量不是多态类,只是基本整数类型之一。或者我错过了什么(很可能)。我想我有 numeric_limits 用于直接使用类型名的情况。现在我可以做类似的事情: e=numeric_limits
::max(); ? -
在编译时,编译器肯定知道类型“a”或“b”。否则编译器根本无法使用这些变量生成代码。
标签: c++ templates compile-time