...

/

Providing Structured Binding Interface for Custom Class

Providing Structured Binding Interface for Custom Class

To work with custom classes, we need three things: 1. std::tuple_size 2. get<N> 3. std::tuple_element

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:

Press + to interact
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:

Press + to interact
// 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, ...