结构化绑定和基于范围的gcc中未使用的警告 [英] structured bindings and range-based-for; supress unused warning in gcc
问题描述
我想使用结构绑定遍历地图,而忽略键:
I want to traverse a map using structure bindings, ignoring the key:
for (auto& [unused, val] : my_map)
do_something(val);
我用gcc-7.2.0尝试了不同的选择:
I have tried different options with gcc-7.2.0:
// The warning is issued
for ([[maybe_unused]] auto& [unused, val] : my_map)
do_something(val);
// Syntax error
for (auto& [[[maybe_unused]] unused, val] : my_map)
do_something(val);
// The same two combinations above with [[gnu::unused]].
似乎 [[maybe_unused]]
属性尚未为结构绑定实现。
It seems that the [[maybe_unused]]
attribute is not implemented yet for structure bindings.
有没有简单的解决方案?任何宏,gcc / gnu扩展名或任何杂用语可以暂时禁止特定警告对我有用;例如,在我使用基于范围的for的整个函数体中将其禁用,因为我使用的此函数非常短(它基本上是两个具有精确行为的不同地图上的两个范围进行循环)。
Is there any simple solution to this? Any macro, gcc/gnu extension, or any pragma to temporarily supress that specific warning is fine to me; for example, disabling it during the whole function body where I'm using the range-based-for, because the function I'm using this is pretty short (it is basically two range-for-loops over two different maps with exact behaviour).
我用来编译项目的(相关)选项是:
The (relevant) options I'm using to compile the project are:
-std=c++17 -Wall -Wextra -Werror -pedantic -pedantic-errors
我要继续做的是,但这很丑陋:
What I have current to go on is, but that's ugly:
for (auto& [unused, val] : my_map)
(void)unused, do_something(val);
推荐答案
相关的GCC编译指示已记录在在此页面上。
The relevant GCC pragmas are documented on this page.
#include <map>
std::map<int, int> my_map;
void do_something(int);
void loop()
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
for (auto & [unused, val]: my_map)
#pragma GCC diagnostic pop
do_something(val);
}
这是我可以禁止的警告的最小范围已经并且仍然通过 -Wall -Wextra -Werror
取消了警告。
This is the smallest scope of the disabled warning that I could have, and still have the warning suppressed with -Wall -Wextra -Werror
.
这篇关于结构化绑定和基于范围的gcc中未使用的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!