Search⌘ K
AI Features

Providing Structured Binding Interface for Custom Class

Explore how to provide structured binding support for your custom classes in C++17. Understand the role of get<N>, tuple_size, and tuple_element specializations that enable unpacking objects into variables. Learn to implement both read-only and writable structured bindings for enhanced code clarity and expressiveness.

We'll cover the following...

You can provide Structured Binding support for a custom class.

To do that you have to define get<N>, std::tuple_size and std::tuple_element specialisations for your type.

For example, if you have a class with three members, but you’d like to expose only its public interface:

C++ 17
class UserEntry {
public:
void Load() { }
std::string GetName() const { return name; }
unsigned GetAge() const { return age; }
private:
std::string name;
unsigned age { 0 };
size_t cacheEntry { 0 }; // not exposed
};

The interface for Structured Bindings:

C++ 17
// with if constexpr:
template <size_t I> auto get(const UserEntry& u) {
if constexpr (I == 0) return u.GetName();
else if constexpr (I == 1) return u.GetAge();
}
namespace std {
template <> struct tuple_size<UserEntry> : std::integral_constant<size_t, 2> { };
template <> struct tuple_element<0,UserEntry> { using type = std::string; };
template <> struct tuple_element<1,UserEntry> { using type = unsigned; };
}

tuple_size specifies how many fields are available, ...