[英]How do I have a platform-dependent check and no -Wtype-limits warning?
I have code like this which is meant to target various compilers and platforms: 我有这样的代码,旨在针对各种编译器和平台:
long value = obtainLongValue();
if(value <= 0)
handleError();
if((unsigned long)value >= (size_t)-1)
handleError();
size_t valueAsSizeT = value;
char* buffer = new char[value + 1];
Thechnically size_t
can be smaller that unsigned long
or the other way around or they can be of the same size. 通常,
size_t
可以小于unsigned long
,也可以相反,或者可以相同。
On some targets both size_t
and unsigned long
are 64-bit and the code actually checks something and compiles cleanly. 在某些目标上,
size_t
和unsigned long
均为64位,并且代码实际上检查了某些内容并进行了干净地编译。 Yet on other targets size_t
is 64-bit and unsigned long
is 32-bit and for such platforms the check is meaningless - long
is never long enough to overflow size_t
- and so gcc emits a warning when used with -WExtra
: 然而,对其他目标
size_t
为64位和unsigned long
是32位,并为这些平台的检查是没有意义的- long
是不会太长溢出size_t
-等GCC发出当用于警告-WExtra
:
warning: comparison is always false due to limited range of data type [-Wtype-limits]
警告:由于数据类型[-Wtype-limits]的范围有限,比较始终为假
gcc is technically correct on those targets, but I need this check in place just in case. gcc在这些目标上在技术上是正确的,但是为了以防万一,我需要进行此检查。
How do I keep the check and have this code compiled cleanly with gcc? 如何保持检查并使用gcc干净地编译此代码?
Use template and specialization: 使用模板和专业化:
template <bool = sizeof(unsigned long) <= sizeof(std::size_t)>
constexpr bool CheckLongLessThanMaxSizeT(unsigned long value)
{
return true;
}
template <>
constexpr bool CheckLongLessThanMaxSizeT<false>(unsigned long value)
{
return value <= static_cast<std::size_t>(-1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.