如何解决禁止在index_sequence上警告“表达式结果未使用”
这个问题的灵感来自this answer。
以下代码会产生未使用值的警告:
#include <array>
#include <vector>
#include <iostream>
#include <utility>
template <size_t... I>
auto f(std::index_sequence<I...>)
{
std::array<std::vector<int>,sizeof...(I)> res{(I,std::vector<int>(3,-1))...};
return res;
}
int main()
{
auto v = f(std::make_index_sequence<2>{});
for (const auto& vec : v)
{
for (const auto& x : vec)
std::cout << x << ' ';
std::cout << '\n';
}
return 0;
}
live on Coliru看到它。
对于gcc
10.1.0,警告是
main.cpp:9:52: warning: left operand of comma operator has no effect [-Wunused-value]
9 | std::array<std::vector<int>,-1))...};
| ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
使用clang
10.0.1时,警告是
main.cpp:9:51: warning: expression result unused [-Wunused-value]
std::array<std::vector<int>,-1))...};
(和一些类似的)。
在c++17
中,属性[[maybe_unused]]
应该允许禁止显示未使用变量的警告。但是,将[[maybe_unused]]
放在f
的参数之前
auto f([[maybe_unused]] std::index_sequence<I...>)
没有效果。
如何抑制以上警告?
解决方法
您可以将I
强制转换为void
以放弃该表达式,并带有警告:
std::array<std::vector<int>,sizeof...(I)> res{
(static_cast<void>(I),std::vector<int>(3,-1))...
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。