assigning members of a pair to variables
The C++17 already let you to use the Structured binding declaration syntax:
#include <iostream>
std::pair<bool, int> foo() {
return std::make_pair(false, 3);
}
int main() {
auto [y, x] = foo(); //Structured binding attribution
std::cout << x << ',' << y << '\n';
}
Yes; std::tie
was invented for this:
#include <tuple>
#include <iostream>
std::pair<bool, int> foo()
{
return std::make_pair(false, 3);
}
int main()
{
int x;
bool y;
std::tie(y, x) = foo();
std::cout << x << ',' << y << '\n';
}
// Output: 3,0
(live demo)
Of course you are still going to have a temporary object somewhere (modulo constant optimisations), but this is the most direct you can write the code unless you initialise x
and y
directly from their eventual values rather than first creating a pair inside foo()
.