Reputation: 372
Inspired by this question I got thinking about what the perfect std::pair
should look like. The compressed pair class (e.g. boost's) provides a pair that is whose size is reduced when one of its types is an empty class. The compressed pair requires getters (first()
, second()
), to hide the fact that the member with an empty type doesn't exist.
Secondly, according to the C++ docs: "Pairs are a particular case of tuple", yet they're implemented as a separate class. Why not use partial template specializations, such as
template <typename ...Args> class tuple {};
template <typename T1, typename T2> class tuple<T1, T2> {}; // Implements a compressed pair
template <typename T1, typename T2> using pair = tuple<T1, T2>;
Further, to provide a more unified API one could overload std::get
and std::set
for pair
, and ditch the first()
and second()
accessors. Or one could have both :)
Why is std::pair
not a specialization of std::tuple
?
When might one use std::pair
instead of a compressed pair? And even if there are cases, should the default be the compressed pair?
Why isn't there a compressed tuple class?
Upvotes: 2
Views: 616
Reputation: 8785
pair
predates tuple
by good 10 years. It exist as a separate class mostly due to historical reasons and for backward compatibility. Making a breaking change to it is more trouble than it worth. If somebody wants tuple with two elements, they can just use tuple with two elements.
I have trouble coming with non-artificial examples, the only real reason I think is using standard library classes, and backward compatibility with code assuming sizeof(pair<A,B>) >= sizeof(A) + sizeof(B)
and similar.
There is no compressed_tuple
as std::tuple
already performs EBO in every standard library implementation worth their salt.
Upvotes: 4