编译时:
const static union {
float cMaskF;
int cMask = -1;
};
x86_64-w64-mingw32-gcc-5.2.0
成功,而 i686-pc-cygwin-gcc-4.9.2
和 4.9.3
出现以下错误:
uninitialized const 'Uphil::Math::{anonymous}::' [-fpermissive]
但是,下面也会产生错误,可以理解...
const static union {
float cMaskF = 1.0f;
int cMask = -1;
};
multiple fields in union 'Uphil::Math::{anonymous}::' initialized
initializations for multiple members of 'Uphil::Math::{anonymous}::'
那么有没有办法让 const static 匿名 union 编译一致呢?这是旧版本中已修复的错误,还是我不希望可移植的“非标准”代码?无论如何,这似乎是一个有用的结构。
这都是在 C++11 下编译的。即使使用 -pedantic
,v5.2.0 也会在没有警告的情况下成功。
最佳答案
据我所知,这似乎是允许 const 匿名 union 的 gcc 扩展。这适用于更高版本的 gcc,对于 example with gcc 5.2 .似乎让它适用于旧版本的唯一方法是使用 -fpermissive标志,它降低了对不一致代码的警告,但这可能是不可取的。
另一方面,如果我们使用 clang 尝试此代码,如果我们使用 -pedantic
标志 ( see it live ),它会提供以下警告:
warning: anonymous union cannot be 'const' [-Wpedantic]
我们可以找到一份 gcc 错误报告:type-specifier const in declaration of anonymous union它声称由于 7.1.6.1
[dcl.type.cv] 其格式错误,它说:
If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list of the declaration shall not be empty.
据我所知这是正确的。根据 9.5
部分的匿名 union 的定义,我们被迫拥有一个空的 init-declarator-list [class.union]:
A union of the form
union { member-specification } ;
is called an anonymous union; it defines an unnamed object of unnamed type.
关于c++ - 静态常量匿名 union 使用 GCC 4.9.3 给出 "uninitialized const"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641531/