Search code examples
c++gcceclipse-cdtstructured-bindings

Can't get std::ignore working in structured bindings in for range


This code compiles and works, with an 'unused variable i' warning:

for(auto [camera, i]: landmark->getObservations())
  camerasToCounts[camera]++;

I want to ignore i, so I replaced it with std::ignore. The following code doesn't compile:

...
#include <tuple>
...
for(auto [camera, std::ignore]: landmark->getObservations())
  camerasToCounts[camera]++;

with this error:

error: expected ‘]’ before ‘::’ token

and this warning:

warning: unused variable ‘std’ [-Wunused-variable]

Because it is not recognizing std::ignore.

Some context:

  • I'm using C++17 with gcc 7.4.0, and Eclipse CDT.
  • Syntax checker shows the same error the compiler does. This is coherent.
  • Same problem in other for range in many cpp files of the same project. It is a general problem, not a particularly bounded to that specific line.
  • Just to test, this line compiles fine:

    std::ignore = 0;

so gcc recognizes std::ignore, it only fails to do so in for range.

Already read this good question and answer about ignoring in structured bindings.

Is there someone with a similar problem?

Thank you!


Solution

  • Structured bindings declares variables1 that bind to the members/elements of the thing being returned. That means you can't use std::ignore since for one it is not a valid variable name and for two it is a name that has apready been declared. If you want to ignore the result, just name the member ignore and don't use it like

    for(auto [camera, ignore]: landmark->getObservations())
        camerasToCounts[camera]++;
    

    1: It actually only creates a single variable that the return value is stored in and then the names in the square brackets are actually references the ith member of the returned object.