1

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?

francesco
  • 7,189
  • 7
  • 22
  • 49

1 Answers1

2

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))...
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 1
    Thanks a lot! According to [this answer](https://stackoverflow.com/a/34289000/8769985), casting to ```void``` appears to be well defined. It's not clear to me what's the difference concerning the warning, given that you already discard the value with the comma operator. – francesco Sep 03 '20 at 22:06
  • @francesco Great that it worked! The warnings is there to just make you pay attention to something that may have been a mistake. When you cast you sort of say "I know what I'm doing". – Ted Lyngmo Sep 03 '20 at 22:07