在 index_sequence 上抑制警告 "expression result unused"

Suppress warning "expression result unused" on a index_sequence

这个问题的灵感来自

以下代码产生未使用值的警告:

#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>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};

      |                                                  ~~^~~~~~~~~~~~~~~~~~~~~~~~~~

with 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]] 应该允许抑制对未使用变量的警告。但是,将 [[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))...
};