Variable cannot appear in a constant-expression

筅森魡賤 提交于 2019-12-24 10:23:30

问题


I'm having a hard time figuring out why GCC 4.5 won't let me compile this:

#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. 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."


回答1:


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.

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


来源:https://stackoverflow.com/questions/12030346/variable-cannot-appear-in-a-constant-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!