简体   繁体   English

可以在C ++中以可移植的方式使用命名属性初始化POD结构吗?

[英]Can POD-structs be initialized using named attributes in a portable way in C++?

I am trying to initialize a struct using named attributes in a way that is compatible both with GCC 4.3.4 and Clang 2.9. 我试图以与GCC 4.3.4和Clang 2.9兼容的方式使用命名属性初始化结构。

struct A {
  unsigned int x;
};

// GCC: error: expected primary-expression before '.' token
A a = {
  .x = 0xdeadbeef;
};

// Clang: error: use of GNU old-style field designator extension [-Werror,-Wgnu-designator]
A a = {
  x : 0xdeadbeef;
};

I cannot add -Wno-gnu-designator to CXXFLAGS because then GCC will refuse to build since it does not know that flag. 我不能将-Wno-gnu-designator添加到CXXFLAGS,因为GCC将拒绝构建,因为它不知道该标志。 I cannot use an initialization list without naming attributes because if the API changes we are going to have serious issues. 我不能在没有命名属性的情况下使用初始化列表,因为如果API发生更改,我们将会遇到严重问题。

The solution I need has to conform to the C++ standard while retaining the fact that if new attributes appear in the struct they should be uninitialized (or preferably NULL). 我需要的解决方案必须符合C ++标准,同时保留以下事实:如果结构中出现新属性,它们应该是未初始化的(或者最好是NULL)。 The structs are third party and I cannot alter them in any way. 结构是第三方,我不能以任何方式改变它们。

No, you cannot name the values, just give them in order. 不,你不能命名这些值,只需按顺序给它们。

A a = { 42 };

If new fields are added at the end of the struct, they will be zeroed. 如果在结构的末尾添加新字段,则它们将被清零。

You could do something like this: 你可以这样做:

#if THIS_IS_GCC
  #define INIT_ATTR(x,y) x : y;
#elif THIS_IS_LLVM
  #define INIT_ATTR(x,y) .x=y;
#else
  #error Can't do it :/
#endif

A a = {
  INIT_ATTR(x,0xdeadbeef)
};

However this is really not standard C++. 然而,这实际上不是标准的C ++。

Is anything wrong with : 有什么不对的:

A a;
a.x = y;

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

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