Judge
Judge

Reputation: 372

The Perfect Pair

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 :)

Questions

  1. Why is std::pair not a specialization of std::tuple?

  2. When might one use std::pair instead of a compressed pair? And even if there are cases, should the default be the compressed pair?

  3. Why isn't there a compressed tuple class?

Upvotes: 2

Views: 616

Answers (1)

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

  1. 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.

  2. 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.

  3. There is no compressed_tuple as std::tuple already performs EBO in every standard library implementation worth their salt.

Upvotes: 4

Related Questions