Structured bindings
suggest changeC++17 introduced structured bindings, which simplify working with multiple values and remove the need for manual tuple unpacking:
std::map<std::string, int> m;
// insert an element into the map and check if insertion succeeded
auto [iterator, success] = m.insert({"Hello", 42});
if (success) {
// your code goes here
}
// iterate over all elements without having to use the cryptic 'first' and 'second' names
for (auto const& [key, value] : m) {
std::cout << "The value for " << key << " is " << value << '\n';
}
Structured bindings work with arrays, tuple-like types such as std::pair and std::tuple, and eligible classes whose non-static data members are accessible from the binding context. The precise inheritance restrictions depend on the selected language version; a class with direct public members is the simplest case:
struct Point { int x; int y; };
Point make_point();
// with structured bindings
const auto [x, y] = make_point();
// equivalent code without structured bindings
const auto result = make_point();
const auto& x = result.x;
const auto& y = result.y;
A user-defined type can opt into tuple-like binding by providing suitable std::tuple_size and std::tuple_element specializations together with get overloads:
namespace my_ns {
struct my_type {
int x;
double d;
std::string s;
};
struct my_type_view {
my_type* ptr;
};
}
namespace std {
template<>
struct tuple_size<my_ns::my_type_view> : std::integral_constant<std::size_t, 3>
{};
template<> struct tuple_element<0, my_ns::my_type_view>{ using type = int; };
template<> struct tuple_element<1, my_ns::my_type_view>{ using type = double; };
template<> struct tuple_element<2, my_ns::my_type_view>{ using type = std::string; };
}
namespace my_ns {
template<std::size_t I>
decltype(auto) get(my_type_view const& v) {
if constexpr (I == 0)
return v.ptr->x;
else if constexpr (I == 1)
return v.ptr->d;
else if constexpr (I == 2)
return v.ptr->s;
static_assert(I < 3, "Only 3 elements");
}
}
Now this works:
my_ns::my_type t{1, 3.14, "hello world"};
my_ns::my_type_view foo() {
return {&t};
}
int main() {
auto [x, d, s] = foo();
std::cout << x << ',' << d << ',' << s << '\n';
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents