1

我很难弄清楚为什么 GCC 4.5 不允许我编译这个:

#include <iostream>
#include <bitset>

#define WIDTH 512
#define HEIGHT 512

#define CEIL_POS(X) ((X - (unsigned int)(X)) > 0 ? (unsigned int)(X + 1) : (unsigned int)(X))

int main ()
{
    const unsigned int length = static_cast<const unsigned int>(CEIL_POS(static_cast<float>(WIDTH * HEIGHT) / 8.0));

    std::bitset<length> bits;

    return 0;
}

它在 VS2010 中运行良好。我错过了什么?

更新:我很着急,我没有粘贴整个代码。对于那个很抱歉 :(

PS:正如标题所说,我收到的错误是:“长度不能出现在常量表达式中。”

4

1 回答 1

1

我不知道您遇到的问题是否是由编译器中的错误引起的,或者这是否是预期的行为,但简单地将 static_cast 删除为 float 似乎可以解决问题,并产生完全相同的值。

#include <iostream>
#include <bitset>

#define WIDTH 512
#define HEIGHT 512

#define CEIL_POS(X) ((X - (unsigned int)(X)) > 0 ? (unsigned int)(X + 1) : (unsigned int)(X))

int main ()
{
    const unsigned int length_1 = static_cast<const unsigned int>(CEIL_POS(static_cast<float>(WIDTH * HEIGHT) / 8.0));
    const unsigned int length_2 = static_cast<const unsigned int>(CEIL_POS(WIDTH * HEIGHT / 8.0));

    std::cout << length_1 << '\n' << length_2 << '\n';
    if (length_1 == length_2)
        std::cout << "They are exactly the same.";

    std::bitset<length_2> bits;
}
于 2012-08-19T22:50:56.500 回答