structured bindings and range-based-for; supress unused warning in gcc

我的未来我决定 提交于 2019-11-30 18:56:10

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);

}

This is the smallest scope of the disabled warning that I could have, and still have the warning suppressed with -Wall -Wextra -Werror.

It seems that you are right that the maybe_unused attribute is not implemented yet for structured bindings in gcc 7.2.0, but it's worth noting that it seems to be implemented for gcc 8.0 trunk (g++ 8.0.0 20171026 experimental).

Compiling using gcc 8.0 trunk, the following will emit a -Wunused-variable warning:

// warning: unused structured binding declaration [-Wunused-variable]
for (auto& [unused, val] : my_map) { }

Whereas this will not:

// no warning
for ([[maybe_unused]] auto& [unused, val] : my_map) { }

Peculiarly, removing [[maybe_unused]] but making use of at least one of the bounded variables will also not yield a warning (intended?).

// no warning
for (auto& [unused, val] : my_map)
{
    do_something(val);
}

// no warning
for (auto& [unused, val] : my_map)
{
    (void)unused;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!