我应该在哪里指定 [[gnu::transparent_union]]

Where should I specify [[gnu::transparent_union]]?

本文关键字:transparent union gnu 在哪里 我应该      更新时间:2023-10-16

Clang 支持对特定于供应商的属性使用 C++11 通用属性语法。这意味着理论上,我可以使用 Clang 支持的任何属性,并使用 [[attribute]] 语法对其进行标记。

但是,我在使用 transparent_union 属性时遇到问题。我记得C++基本上可以让您将属性放在任何地方,所以我尝试了以下所有方法,但无济于事:

[[gnu::transparent_union]] union x { int foo; };
// error: an attribute list cannot appear here
union [[gnu::transparent_union]] x { int foo; };
// warning: transparent_union attribute can only be applied to a union definition;
// attribute ignored [-Wignored-attributes]
union x [[gnu::transparent_union]] { int foo; };
// error: an attribute list cannot appear here
// warning: transparent_union attribute can only be applied to a union definition;
// attribute ignored [-Wignored-attributes]
union x { int foo; } [[gnu::transparent_union]];
// error: an attribute list cannot appear here
// warning: transparent_union attribute can only be applied to a union definition;
// attribute ignored [-Wignored-attributes]

使用 __attribute__ 语法的正确位置似乎是联合定义的末尾:

union x { int foo; } __attribute__((transparent_union));
// OK
如果有

的话,在哪里放置[[gnu::transparent_union]]与 Clang 在一起?

在 C++11 标准中,它在语法中显示属性说明符 seq类键之后,这就是 union 是什么。

      班长:       class-key 属性说明符-seq opt 类头名称 class-virt-specifier opt base-clauseopt       类键属性说明符-seqopt 基句选项[..]类键:       .class       结构       联盟

这被确认为:

union [[gnu::transparent_union]] x { int foo; };

似乎是唯一不会引发诊断的语法。所以也许这是一个叮当虫。

请记住,__attribute__似乎是GNU扩展,而[[attribute]]是C++的一部分。