1

I have a function:

std::tuple<int, int> func(int x) {
    int a = x + 1;
    int b = x + 2;
    return { a, b };
}

and call it as:

auto [a, b] = func(3);

Now I only need b. How can I suppress or ignore the output of a? Similar to MATLAB [~, b] = func(3).

WDC
  • 334
  • 1
  • 3
  • 14
  • `auto [_, b] = func(3);` is often used. `_` (single underscore) happens to be a valid identifier. – Igor Tandetnik Feb 03 '20 at 04:49
  • Would [std::ignore](https://en.cppreference.com/w/cpp/utility/tuple/ignore) be what you are looking for? – ExaltedBagel Feb 03 '20 at 04:51
  • @IgorTandetnik What if there are three, say `auto [a, b, c] = func(3)` ? I got `error: redefinition of '_'` for my real function, where I am calling `auto [_, _, c] = func(3)`. – WDC Feb 03 '20 at 04:51
  • 1
    @ExaltedBagel `std::ignore` doesn't work with structured bindings. The syntax expects a plain identifier. – Igor Tandetnik Feb 03 '20 at 04:53
  • @IgorTandetnik I see, I could use `auto [_, __, c] = func(3)` for three outputs. But are there any more elegant ways to handle situations like this? Thanks. – WDC Feb 03 '20 at 04:56
  • You could invent a naming convention, e.g. `auto [_1, _2, c] = func(3);`. I don't believe there's anything better at the moment, any special placeholder for an ignored value. – Igor Tandetnik Feb 03 '20 at 04:56
  • 1
    Doesn't seem like this is supported: https://stackoverflow.com/questions/40673080/stdignore-with-structured-bindings. In Python/C++ I typically do [_, __, (onward), b] = – tangy Feb 03 '20 at 04:57
  • 3
    Careful - names containing double underscores are reserved for the implementation. – Igor Tandetnik Feb 03 '20 at 04:57
  • Thanks for the heads up @IgorTandetnik - didn't realize this earlier. – tangy Feb 03 '20 at 04:58
  • @IgorTandetnik I believe the issue has been resolved. Would you mind expanding your comments into a small answer? Thanks again. – WDC Feb 03 '20 at 05:01
  • 2
    `auto b = std::get<1>(func(3));` if you want only one component. ;-) – Jarod42 Feb 03 '20 at 08:59

0 Answers0