c++ - 与 [[maybe_unused]] 的结构化绑定(bind)

标签 c++ c++17 structured-bindings

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

有了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)。它按预期工作(也可能更早):

  • gcc 8.0 主干(g++ 8.0.0 20171015 实验性)
  • clang 4.0.0
  • icc 18(未经测试,根据 specs)
  • msvc 19.22(可能更早)(已修复,根据 bug report)

在godbolt 中试用https://gcc.godbolt.org/z/H2duYd

最佳答案

在结构绑定(bind)论文中:

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]],但我认为推理可能是相同的。停止编译器警告不是用例。

关于c++ - 与 [[maybe_unused]] 的结构化绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404001/

相关文章:

c++ - 模板类 std::valarray<T> 推导指南

c++ - 具有 std::map 和 std::variant 的不完整类型

c++ - 为什么包含 <utility> 会破坏 GCC 中的结构化绑定(bind)?

c++ - C++17 中结构化绑定(bind)引入的标识符有哪些类型?

c++ - 在 MATLAB 中预分配内存 à la std::vector::reserve(n)

c++ - C++ 17中的拟态std::bind_front用于调用成员函数

c++ - 我的部分模板特化的模板参数不可推导

c++ - std::reduce 对于 float 有多安全?

php - 我应该在 switch 语句中使用 continue 吗?