0 day streak
cpp / expert
Snippet

Decomposing Objects with Custom Structured Bindings

Structured bindings allow you to unpack objects into separate variables. For custom types, you must specialize 'std::tuple_size' and 'std::tuple_element', and provide a 'get' function. This enables clean, readable syntax for complex data structures.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <tuple>
struct Player {
std::string name;
int score;
};
namespace std {
template<> struct tuple_size<Player> : integral_constant<size_t, 2> {};
template<> struct tuple_element<0, Player> { using type = std::string; };
template<> struct tuple_element<1, Player> { using type = int; };
}
template<size_t I> auto& get(Player& p) {
if constexpr (I == 0) return p.name;
else if constexpr (I == 1) return p.score;
}
int main() {
Player p{"Alice", 100};
auto& [n, s] = p; // Structured binding
s += 50;
std::cout << p.name << ": " << p.score << std::endl;
return 0;
}
Breakdown
1
auto& [n, s] = p;
Binds variables 'n' and 's' directly to the members of 'p' by reference.
2
if constexpr (I == 0)
Compile-time conditional used to select the correct member during template instantiation.