1

I'm extracting a tuple with auto [...] but I'm only using some of the tuple coordinates. I wanted to know if there is some elegant way to avoid the unused-variable compiler warning? Here is my code.

#include <iostream>
#include <vector>
#include <tuple>

int main(int argc, char **argv)
{
    std::vector<std::tuple<char,float,int>> myvec;
    myvec.push_back(std::make_tuple('a',3.5,8));
    myvec.push_back(std::make_tuple('b',1.5,4));
    auto [c,f,_] = myvec[1];
    std::cout << "char float is " << c << " " << f << "\n";
    return 0;
}

And here is the compilation line + warning:

$ g++ -Wall -std=c++17 main.cpp -o main
main.cpp: In function ‘int main(int, char**)’:
main.cpp:10:13: warning: unused variable ‘_’ [-Wunused-variable]
  auto [c,f,_] = myvec[1];
             ^

(I used a Haskell-like variable _ to self document the fact that the last int is a don't-care value).

L. F.
  • 19,445
  • 8
  • 48
  • 82
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 1
    Self documentation is a good idea, but using `_` is problematic. Use `ignored` for the same noble purpose. – Yunnosch Sep 21 '19 at 05:32
  • 1
    Possible duplicate of [structured binding with \[\[maybe\_unused\]\]](https://stackoverflow.com/questions/41404001/structured-binding-with-maybe-unused) – L. F. Sep 21 '19 at 05:40
  • Why not just extract elements of interest one by one without structed bindings? Note that in general case creating an unused variable may lead to overhead. – user7860670 Sep 21 '19 at 05:41
  • 1
    C++20 recommends that implementations *should* not emit a warning if any of the variables is used. – L. F. Sep 21 '19 at 05:49
  • I would also like to know your `g++ --version`. – Yunnosch Sep 21 '19 at 05:56
  • @Yunnosch I pasted the exact and entire compiler message. it only complains about the unused `_`. I'm using `gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0` – OrenIshShalom Sep 21 '19 at 05:56
  • [[maybe_unused]] did not solve my problem. What `g++` version is needed for this? – OrenIshShalom Sep 21 '19 at 06:06

0 Answers0