std::tuple#include <tuple> groups any number of values into a single object:
// Tuple with 3 elements.
std::tuple#include <tuple><std::string#include <string>, int, double> t("alice", 30, 1.7);
// Tuple with 5 elements.
std::tuple#include <tuple><int, int, double, int, std::string#include <string>> u(-3, 30, 1.7, 0, "str");
// Tuple with 6 elements.
std::tuple#include <tuple><char, char, char, char, char, char> v('a', 'b', 'c', 'd', 'e', 'f');std::tuple#include <tuple> is available from the tuple header:
#include <tuple>Tuple elements are accessed by index with std::get#include <tuple>. The index is a template argument and must be known at compile time:
std::get#include <tuple><0>(t); // "alice"
std::get#include <tuple><1>(t); // 30
std::get#include <tuple><2>(t); // 1.7
std::get#include <tuple><1>(t) = 31;std::make_tuple#include <tuple> creates a tuple without writing out the types. The function deduces the types from the arguments:
// std::tuple#include <tuple><const char*, int, double>
auto t = std::make_tuple#include <tuple>("alice", 30, 1.7);Tuples are often used to return several values 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);
}
std::tuple#include <tuple><int, int, int> result = stats(5, 3);
std::get#include <tuple><0>(result); // 8
std::get#include <tuple><1>(result); // 2
std::get#include <tuple><2>(result); // 15Note
Tuples are best used for short-lived groups of values and accessing a tuple with std::get#include <tuple><1> is non-descriptive. Prefer a struct with named fields when the values belong together and will be used across the program.
Dan