是什么,如果发生整数截断检测的最佳方式?
编辑
这应当引起截断而被发送信号,但它不会
#include <iostream>
using std::cout;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
int32_t my32bitInt = 0xffffffff;
int32_t tmp = my32bitInt & 0xFFFF8000;
uint16_t ss = my32bitInt;
int main()
{
if (tmp != 0xFFFF8000 && tmp != 0x00000000)
{ // cannot be converted safely
cout << "truncation";
}
cout << ss << '\n';
cout << my32bitInt << '\n';
return 0;
}
编辑2
template <typename U, typename T>
bool is_safe(T t)
{
return sizeof(U) <= sizeof(T) ?
(t >= static_cast<T>(std::numeric_limits<U>::min()))
&& (t <= static_cast<T>(std::numeric_limits<U>::max())) : true;
}
编辑3(基于奥利奇的<>) - 我发现了一些问题,但在它的工作,将尽快更新
模板 布尔is_safe(来源值) {
if (sizeof(Result) == sizeof(Source))
{/*Same size*/
if (std::is_same<Source,Result>::value)
{
//signed to signed or unsigned to unsigned when size is same - no problem
return true;
}
else
{
//MSB mustn't be set in Source
return !(value & (1u << ((sizeof(Source) * CHAR_BIT) - 1)));
}
}
else
{//smaller to larger and larger to smaller
if (sizeof(Result) <= sizeof(Source))
{ //Larger to smaller and both equal
return ((value >= static_cast<Source>(std::numeric_limits<Result>::min()))
&& (value <= static_cast<Source>(std::numeric_limits<Result>::max())));
}
else
{ //smaller to larger
if (std::is_signed<Source>::value && !std::is_signed<Result>::value)
{
//signed to unsigned - signed must be positive
return (value >= 0);
}
else
{
return true;
}
}
}
}
你是什么意思的“截断”?溢出? – Mat 2011-04-16 09:18:58
本周早些时候我以为我看到了这个问题,但我现在找不到它。 – 2011-04-16 09:27:53
也许'整数截断'是整数溢出例如另外。或者,当转换为更窄的类型时可能会丢失数据? – 2011-04-16 09:32:10