What is std::pair?
compressed_pair
uses some template trickery to save space. In C++, an object (small o) can not have the same address as a different object.
So even if you have
struct A { };
A
's size will not be 0, because then:
A a1;
A a2;
&a1 == &a2;
would hold, which is not allowed.
But many compilers will do what is called the "empty base class optimization":
struct A { };
struct B { int x; };
struct C : public A { int x; };
Here, it is fine for B
and C
to have the same size, even if sizeof(A)
can't be zero.
So boost::compressed_pair
takes advantage of this optimization and will, where possible, inherit from one or the other of the types in the pair if it is empty.
So a std::pair
might look like (I've elided a good deal, ctors etc.):
template<typename FirstType, typename SecondType>
struct pair {
FirstType first;
SecondType second;
};
That means if either FirstType
or SecondType
is A
, your pair<A, int>
has to be bigger than sizeof(int)
.
But if you use compressed_pair
, its generated code will look akin to:
struct compressed_pair<A,int> : private A {
int second_;
A first() { return *this; }
int second() { return second_; }
};
And compressed_pair<A,int>
will only be as big as sizeof(int).
std::pair
is a data type for grouping two values together as a single object. std::map
uses it for key, value pairs.
While you're learning pair
, you might check out tuple
. It's like pair
but for grouping an arbitrary number of values. tuple
is part of TR1 and many compilers already include it with their Standard Library implementations.
Also, checkout Chapter 1, "Tuples," of the book The C++ Standard Library Extensions: A Tutorial and Reference by Pete Becker, ISBN-13: 9780321412997, for a thorough explanation.
You sometimes need to return 2 values from a function, and it's often overkill to go and create a class just for that.
std:pair comes in handy in those cases.
I think boost:compressed_pair is able to optimize away the members of size 0. Which is mostly useful for heavy template machinery in libraries.
If you do control the types directly, it's irrelevant.