与 [[maybe_unused]] 的结构化绑定

structured binding with [[maybe_unused]]

具有模式匹配(有时?)的函数式语言有可能忽略某些绑定值,但对于 C++17 结构化绑定,似乎无法做到这一点 ()。建议是使用虚拟名称,但随后我们会收到有关未使用变量的警告。

有了 clang 和 gcc 的最新版本,这达到了预期的效果,很好用,

[[maybe_unused]] auto x =4 ; // fine, no warning
[[maybe_unused]] auto [a,dummyb,dummyc] = std::tuple<int,int,float>(1,1,1.0f); 

但我也希望这会起作用:

auto [g,[[maybe_unused]]dummyh,[[maybe_unused]]dymmyi] =
      std::tuple<int,int,float>(1,1,1.0f);

这里不能使用attributes有什么具体原因吗? (在标准和技术上)。 gcc 或 clang 都不接受这个。


编辑,收集支持状态:(感谢godbolt/compiler explorer)。它按预期工作(也可能更早):

https://gcc.godbolt.org/z/H2duYd

的 Godbolt 中试用

在结构绑定文件中:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0144r2.pdf

他们讨论他们的推理:

3.8 Should there be a way to explicitly ignore components?

The motivation would be to silence compiler warnings about unused names.

We think the answer should be “not yet.” This is not motivated by use cases (silencing compiler warnings is a motivation, but it is not a use case per se), and is best left until we can revisit this in the context of a more general pattern matching proposal where this should fall out as a special case.

Symmetry with std::tie would suggest using something like a std::ignore:

   tuple<T1,T2,T3> f(); 
   auto [x, std::ignore, z] = f(); // NOT proposed: ignore second element 

However, this feels awkward.

Anticipating pattern matching in the language could suggest a wildcard like _ or *, but since we do not yet have pattern matching it is premature to pick a syntax that we know will be compatible. This is a pure extension that can wait to be considered with pattern matching.

虽然这没有明确解决 [[maybe_unused]],但我认为推理可能是相同的。停止编译器警告不是用例。

作为 CWG 2360, the working draft of the standard gained the following wording ([dcl.attr.unused] 的决议):

  1. The attribute may be applied to the declaration of a class, a typedef-name, a variable (including a structured binding declaration), a non-static data member, a function, an enumeration, or an enumerator.

  2. For an entity marked maybe_unused, implementations should not emit a warning that the entity or its structured bindings (if any) are used or unused. For a structured binding declaration not marked maybe_unused, implementations should not emit such a warning unless all of its structured bindings are unused.

之前没有明确提及结构化绑定声明。