In reading this summary of the c++17 final features I was a bit surprised by the section on structured bindings (emphasis mine):
structured bindings
Until now, there was a known trick to abuse std::tie to assign a tuple or pair to different variables directly, instead of having to deal with the result type manually. This was a hack, and also the variables had to exist, now you can declare the variables and initialize them in one line:
auto [a , b , c] = getvalues();
The braces are needed, getvalues returns a tuple. std::pair is not mentioned in the proposal, so its unclear if this works with pair, which is returned by the STL in some insert methods.
I am assuming they refer to this kind of usage of std::tie
int a,b,c;
std::tie(a,b,c) = std::make_tuple(1,2,3);
which I believed to be a recommended practice.
Can someone offer an explanation as to why they are referring to above example as a hack?
std::tie
in itself has another functionality.It was meant for creating a tuple with references to variables
This is useful for creating on-the-fly tuples without having to copy the variables because they are references. I just take the example from cppreference for a usecase.
Here tuples are created but they don't copy the variables but have references.
Now because they hold references you could "hack" it to do something like this
It assigns the values of the returned tuple to the one with the references in itself.
This is even on cpprefence just mentioned as a "note"
So in c++11 was not really an official way to directly assign values but
std::tie
can be used as this but maybe was never intended to be used that way.So they introduced the new "structured binding".
Whether
std::tie
was meant to be used that way or is a "hack" may be personal opinion, I guess the people who introducedstd::tie
know best for this. But considering how structured binding kind of replacesstd::tie
in that instance, they came up with a solution they think is better.I can put it simply like that:
In a language where functions can return just one variable
is a hack for:
just as in the hypothetical world where C++ would allow just one parameter for functions
would be a hack for:
You are so accustomed with the C++ restriction that a function can return at most one object, but in fact it is just an artificial language restriction, just as a restriction to accept at most one parameter would be an artificial language restriction.
The
std::tie
is a library hack for a missing language feature. And it has some drawbacks:Are structured bindings everything that they could have been? No, but for the most cases they are everything we need.
What is missing?
where
a
andc
have the type deduced andb
is explicit "std::string"where the second returned object from
foo
is atuple
like object.std::tuple
all together):instead of
... well... wouldn't that be nice