是什麼,如果發生整數截斷檢測的最佳方式?
編輯
這應當引起截斷而被髮送信號,但它不會
#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