浮动到int cast而不转换为constexpr用于switch

时间:2016-10-10 05:06:02

标签: c++ casting floating-point bit-manipulation floating-point-conversion

到目前为止,我在switch语句之外工作,但我真的想要打开const float。

typedef union IntAndFloat
{
    float fvalue;
    uint32_t uivalue;
    int32_t ivalue;
};

constexpr uint32_t FloatToIntImpl(const IntAndFloat value) { return value.uivalue; }
constexpr uint32_t FloatConst(const float value) { return FloatToIntImpl({value});  }

int main()
{
    cout << FloatConst(1.0f) << endl;
    switch(0x3f800000)
    {
        case FloatConst(1.0f): cout << "hit" << endl; break;
    }

//example 2

//ugly version
int val = 0x3f800000;
switch (val)
{
    case 0xbf800000: cout << "-1" << endl; break;
    case 0x80000000://neg 0
    case 0x00000000: cout << "0" << endl; break;
    case 0x3f800000: cout << "1" << endl; break;
    case 0x40000000: cout << "2" << endl; break;
    case 0x40400000: cout << "3" << endl; break;
    case 0x40800000: cout << "4" << endl; break;
    case 0x40A00000: cout << "5" << endl; break;
    case 0x40C00000: cout << "6" << endl; break;
    case 0x40E00000: cout << "7" << endl; break;
    default: cout << IntToFloat(val) << endl;

}

//clean nice looking version
int val = FloatConst(1f);
switch (val)
{
    case FloatConst(-1f): cout << "-1" << endl; break;
    case FloatConst(-0f)://neg 0
    case FloatConst(0f): cout << "0" << endl; break;
    case FloatConst(1f): cout << "1" << endl; break;
    case FloatConst(2f): cout << "2" << endl; break;
    case FloatConst(3f): cout << "3" << endl; break;
    case FloatConst(4f): cout << "4" << endl; break;
    case FloatConst(5f): cout << "5" << endl; break;
    case FloatConst(6f): cout << "6" << endl; break;
    case FloatConst(7f): cout << "7" << endl; break;
    default: cout << IntToFloat(val) << endl;
}

}

在gcc中构建你得到:

error: accessing 'IntAndFloat::uivalue' member instead of initialized 'IntAndFloat::fvalue' member in constant expression

除此之外,我还不知道其他任何方式。

inline uint32_t FloatToUInt(float x) { return *(uint32_t*)&x; }

然而,这不是恒定的。

我甚至不确定这是否可行,是否应该是这样。

0 个答案:

没有答案