变量不能出现在常量表达式中 [英] Variable cannot appear in a constant-expression

查看:1549
本文介绍了变量不能出现在常量表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找出为什么GCC 4.5不会让我编译这个:

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

它在VS2010工作正常。我缺少什么?

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:正如标题所说,我收到的错误是:长度不能出现在常量表达式。

PS: Just as the title says, the error that I receive is: "length cannot appear in a constant-expression."

推荐答案

我不知道你所遇到的问题是由编译器中的错误引起的,还是这是预期的行为,只是删除static_cast到float似乎解决了这个问题,并产生了完全相同的值。

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

这篇关于变量不能出现在常量表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆