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

标签 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:正如标题所说,我收到的错误是:“length cannot appear in a constant-expression.”

最佳答案

我不知道你遇到的问题是否是由编译器中的错误引起的,或者这是否是预期的行为,但简单地将 static_cast 移除为 float 似乎可以解决问题,并且结果完全相同值(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;
}

关于c++ - 变量不能出现在常量表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12030346/

相关文章:

c - free() 是否将内存归零?

c++ - 避免或改进暴力破解方法 : Counting character repetition from all words in a dictionary text file

c++ - 迭代器等价于空指针?

c++ - 如何创建加密的挂载文件夹

C# 并从 Excel 文件读取值

C++通过字符串名称调用不同的函数

c++ - CreateProcess的第二个参数应该是什么?

c# - 在 Outlook 2013 上使用 2010 VSTO outlook 插件有问题吗?

gcc - 了解基本的内联 NEON 组装

c++ - 为什么 gcc 警告 decltype(main()) 而不是 clang?