Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++17: Keep only some members when tuple unpacking

Tags:

c++

tuples

c++17

Let's imagine you need to call the following method:

std::tuple<int, int, int> foo();

In C++17, you can call the function and unpack the tuple in a single line:

auto [a, b, c] = foo();

Now, how can I proceed to store only b and c and to discard a?

Currently, I'm only aware of two options:


1 - I can use a dummy variable when auto-unpacking

However, the dummy variable will be unused and it will issue a warning, so if I want to silent that warning the code will be quite unpleasant to see:

#pragma warning(push)
#pragma warning(disable:4101)
// ReSharper disable once CppDeclaratorNeverUsed
auto [_, b, c] = foo();
#pragma warning(pop)

2 - I can store the whole tuple and use std::get to retrieve the reference to the only variables I need. The code is less unpleasant but the syntax is also less straightforward.

Moreover, this code's size increases by one line for each new value that we want keep in the tuple.

auto tuple = foo();
int b = std::get<1>(tuple);
int c = std::get<2>(tuple);

Is there another and more straightforward method to unpack only some parameters in a tuple?

like image 526
Antoine C. Avatar asked May 04 '18 13:05

Antoine C.


2 Answers

Another alternative is to use an std::tie:

int b, c;
std::tie(std::ignore, b, c) = foo();

Edit

As mentioned in the comments, there are some issues with this approach:

  • No type inference possible
  • The objects must be constructed before, so unless the default constructors are trivial, it's not a good alternative.
like image 105
Mansuro Avatar answered Nov 20 '22 04:11

Mansuro


Unfortunately structured bindings do not explicitly support discarding members, and attributes such as [[maybe_unused]] cannot be applied to structured bindings (there's a proposal for that: P0609: "Attributes for Structured Bindings").

Here's a possible solution:

auto [a, b, c] = foo();
(void) a; // unused
like image 46
Vittorio Romeo Avatar answered Nov 20 '22 02:11

Vittorio Romeo