简体   繁体   English

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

[英]Variable cannot appear in a constant-expression

I'm having a hard time figuring out why GCC 4.5 won't let me compile this: 我很难弄清楚为什么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;
}

It works just fine in VS2010. 它在VS2010中工作正常。 What am I missing? 我想念什么?

UPDATE: I was in a hurry and I didn't paste the entire code. 更新:我很着急,没有粘贴整个代码。 Sorry about that :( 对于那个很抱歉 :(

PS: Just as the title says, the error that I receive is: "length cannot appear in a constant-expression." PS:正如标题所述,我收到的错误是:“长度不能出现在常量表达式中。”

I don't know whether the problem you're having is caused by a bug in the compiler, or if that is expected behavior, but simply removing the static_cast to float seems to solve the problem, and results in the exact same value. 我不知道您遇到的问题是由编译器中的错误引起的,还是由预期的行为引起的,但仅将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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM