Why is std::pair<A,B>
not the same as std::tuple<A,B>
? It always felt strange to not be able to just substitute one with the other. They are somewhat convertible, but there are limitations.
I know that std::pair<A,B>
is required to have the two data members A first
and B second
, so it can't be just a type alias of std::tuple<A,B>
. But my intuition says that we could specialize std::tuple<A,B>
, that is a tuple with exactly two elements, to equal the definition of what the standard requires a std::pair
to be. And then alias this to std::pair
.
I guess this wouldn't be possible as it is too straight-forward to not to be already thought of, yet it wasn't done in g++'s libstdc++ for example (I didn't look at the source code of other libraries). What would the problem of this definition be? Is it "just" that it would break the standard library's binary compatibility?
The Tuple is an object capable to hold a collection of elements, where each element can be of different types. The pair can make a set of two values, which may be of different types. The pair is basically a special type of tuple, where only two values are allowed.
A tuple is an object capable to hold a collection of elements where each element can be of a different type. The class template needs the header <tuple> . std::tuple is a generalization of std::pair. You can convert between tuples with two elements and pairs.
std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.
It is fully expected that std::tuple will be slower than std::pair when not optimized, because it is more complicated object.
You've gotta be careful about things like SFINAE and overloading. For example, the code below is currently well-formed but you would make it illegal:
void f(std::pair<int, int>);
void f(std::tuple<int, int>);
Currently, I can disambiguate between pair and tuple through overload resolution, SFINAE, template specialization, etc. These tools would all become incapable of telling them apart if you make them the same thing. This would break existing code.
There might have been an opportunity to introduce it as part of C++11, but there certainly isn't now.
This is purely historical. std::pair
exist since C++98 whereas tuple came after and was initially not part of the standard.
Backward compatibility is the biggest burden for C++ evolution, preventing some nice things to be done easily !
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