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?
[[maybe_unused]]
.std::tie
withstd::ignore
.[[maybe_unused]]
applied to a structured binding declaration, as do clang and GCC. Clang and GCC also suppress the "not used" warning if at least one of the structured bindings in the entire declaration used - I'll implement the same logic in ReSharper C++ (RSCPP-22313). It seems to me that MSVC should support both of these mechanisms, probably worth filing a request with them.