Would it be possible to implement C++17 structured bindings using C++14? I am targetting a simple proof of concept with the following syntax:
int a,b;
(a,b)=std::tuple<int,int>(4,2);
The way I imagined it is :
template <typename T, typename U>
operator=(operator()(T a, U b), std::tuple<T,U>(x,y))
So the =
receives a "tied tuple" left and assigns the right to it.
Would this even be possible? - Is it implementable with C++14, or does lexing/parsing need to take place in the background to enable it?
EDIT Is this possible without using std::tie
, but using the (a,b) syntax?
Sure. This even already exists in the standard library as std::tie()
:
std::tie(a, b) = std::make_tuple(4, 2);
Note that this only works for tuples on the right-hand side. You could fairly straightforwardly extend this to work for raw arrays. But getting it to work for aggregates is much harder - without extra language support you'd need magic_get for that.
If you literally want:
(a, b) = std::make_tuple(4, 2);
to work, then the only way to do that is basically trash all the rest of the code you have by adding a global operator,()
that does std::tie()
for you:
template <typename T, typename U>
auto operator,(T& t, U& u) { return std::tie(t, u); }
template <typename... T, typename U>
auto operator,(std::tuple<T&...> t, U& u) { return std::tuple_cat(t, std::tie(u)); }
So that:
(a, b) = std::make_tuple(4, 2);
itself transforms into:
std::tie(a, b) = std::make_tuple(4, 2);
But like... don't do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With