变量不能出现在常量表达式中

时间:2012-08-19 21:57:12

标签: c++ visual-studio-2010 gcc constant-expression

我很难搞清楚为什么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:正如标题所说,我收到的错误是:“长度不能出现在常量表达式中。”

1 个答案:

答案 0 :(得分:1)

我不知道你所遇到的问题是由编译器中的错误引起的,还是由于预期的行为,但只是将static_cast移除到浮动似乎可以解决问题,并导致完全相同值。

#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;
}