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

  • A+
Category:Languages

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?


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: