I'm trying to implement a wrapper class for another class that has a private std::tuple member and enable structured bindings on the wrapper class. Here's the class with the private tuple:
class widget {
friend class wrap;
std::tuple<int, double> m_tuple {1, 1.0};
};
Here's my attempt at the wrapper class after reading about how to enable structured bindings for custom types (e.g., this post on devblogs.microsoft.com):
class wrap {
public:
wrap(widget& f) : m_tuple(f.m_tuple) {}
// auto some_other_function();
template<std::size_t Index>
auto get() & -> std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
template<std::size_t Index>
auto get() && -> std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
template<std::size_t Index>
auto get() const& -> const std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
template<std::size_t Index>
auto get() const&& -> const std::tuple_element_t<Index, wrap>& {
return std::get<Index>(m_tuple);
}
private:
std::tuple<int, double>& m_tuple;
};
Here are the specialized std::tuple_size and std::tuple_element for wrap:
namespace std {
template<>
struct tuple_size<wrap> : tuple_size<std::tuple<int, double>> {};
template<size_t Index>
struct tuple_element<Index, wrap> : tuple_element<Index, tuple<int, double>> {};
} // namespace std
I'd like the following behavior:
int main() {
widget w;
auto [i_copy, d_copy] = wrap(w);
i_copy = 2; // Does not change w.m_tuple because i_copy is a copy of std::get<0>(w.m_tuple).
d_copy = 2.0; // Does not change w.m_tuple because d_copy is a copy of std::get<1>(w.m_tuple).
// w.m_tuple still holds {1, 1.0}.
auto& [i_ref, d_ref] = wrap(w);
i_ref = 2; // Changes w.m_tuple because i_ref is a reference to std::get<0>(w.m_tuple).
d_ref = 2.0; // Changes w.m_tuple because d_ref is a reference to std::get<1>(w.m_tuple).
// w.m_tuple now holds {2, 2.0}.
}
But this doesn't even compile (tested with gcc 12.2.0 and clang 14.0.6). The error I get is
error: cannot bind non-const lvalue reference of type ‘wrap&’ to an rvalue of type ‘wrap’
| auto& [i_ref, d_ref] = wrap(w);
Does the non-const lvalue reference of type ‘wrap&’ refer to auto& [i_ref, d_ref] and the rvalue of type ‘wrap’ to wrap(w)? Why are i_ref and d_ref not references to the integer and double of the tuple in w?
Edit: How can I implement a wrapper class that has the desired behavior?