Search code examples
attributesc++17suppress-warnings

Suppress warning "expression result unused" on a index_sequence


This question is inspired by this answer.

The following code produces a warning of an unused value:

#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;
}

See it live on Coliru.

With gcc 10.1.0 the warning is

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 the warning is

main.cpp:9:51: warning: expression result unused [-Wunused-value]
  std::array<std::vector<int>, sizeof...(I)> res{(I, std::vector<int>(3, -1))...};

(and some similar ones).

In c++17 the attribute [[maybe_unused]] should allow to suppress warnings on unused variables. However, putting [[maybe_unused]] before the argument of f

auto f([[maybe_unused]] std::index_sequence<I...>)

has no effect.

How can one suppress the above warning?


Solution

  • You can cast I to void to discard the expression, and with it, the warning:

    std::array<std::vector<int>, sizeof...(I)> res{
        (static_cast<void>(I), std::vector<int>(3, -1))...
    };