この質問は、この回答からインスピレーションを得たものです。
次のコードは、未使用の値の警告を生成します。
#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;
}
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>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};
| ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
clang 10.0.1 では警告が表示されます
main.cpp:9:51: warning: expression result unused [-Wunused-value]
std::array<std::vector<int>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};
(および類似のもの)。
C++17 では、属性 [[maybe_unused]] を使用して、未使用の変数に対する警告を抑制できるようにする必要があります。ただし、f の引数の前に [[maybe_unused]] を置きます
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))...
};
2
1
ありがとうございます!この回答によると、void へのキャストは明確に定義されているようです。すでにカンマ演算子を使用して値を破棄していることを考えると、警告に関する違いが明確ではありません。
– フランチェスコ
2020 年 9 月 3 日 22:06
@francesco うまくいってよかったです!警告は、間違いの可能性があることに注意を払うためにあります。キャストするときは、「自分が何をしているのかわかっています」と言っているようなものです。
– テッド・リングモ
2020 年 9 月 3 日 22:07