std::tie#include <tuple> creates a tuple of references to existing variables. Assigning a tuple to it writes each element into the matching variable:
int a;
int b;
std::tie#include <tuple>(a, b) = std::make_tuple#include <tuple>(1, 2); // a = 1, b = 2std::tie#include <tuple> is available from the tuple header:
#include <tuple>It is commonly used to unpack several values returned from a function:
std::tuple#include <tuple><int, int, int> stats(int a, int b) {
return std::make_tuple#include <tuple>(a + b, a - b, a * b);
}
int sum;
int diff;
int prod;
std::tie#include <tuple>(sum, diff, prod) = stats(5, 3); // 8, 2, 15A std::pair#include <utility> can be unpacked the same way:
std::pair#include <utility><int, int> divide(int a, int b) {
return {a / b, a % b};
}
int quotient;
int remainder;
std::tie#include <tuple>(quotient, remainder) = divide(7, 2); // 3, 1std::ignore skips an element that is not needed:
int sum;
int prod;
std::tie#include <tuple>(sum, std::ignore, prod) = stats(5, 3); // 8, 15std::tie#include <tuple> is also a concise way to compare several values at once. Tuples compare element by element from left to right, so this compares by age and then by name only when the ages are equal:
struct Person {
std::string#include <string> name;
int age;
};
bool younger(const Person& a, const Person& b) {
return std::tie#include <tuple>(a.age, a.name) < std::tie#include <tuple>(b.age, b.name);
}Note
The variables must already exist since std::tie#include <tuple> takes references to them. To declare and unpack in one step, use structured bindings.
Dan