compressed_pair and private inheritance

M

Marc

When we implement a pair or a tuple, and one of the objects is empty,
we usually implement it with private inheritance to benefit from the
empty base class optimization:

class pair {
Empty first;
Real second;
public:
// ... some accessors
};

becomes:

class pair : private Empty {
Real second;
public:
// ... some accessors
};

Now in a templated version, we don't know in advance if the first type
will be empty (let us ignore the possibility that the second type may
be empty for now), so we dispatch based on is_empty<First>::value to
use the second implementation if it is empty and the first otherwise .

At least that's what I have seen in every implementation so far.
However, it seems to me that the second implementation should work
whether the type is empty or not, and one implementation is better
than two.

I am probably missing something here, could you tell me what are the
advantages of the first version when the type is not empty?
 
H

Howard Hinnant

When we implement a pair or a tuple, and one of the objects is empty,
we usually implement it with private inheritance to benefit from the
empty base class optimization:

class pair {
  Empty first;
  Real second;
public:
// ... some accessors

};

becomes:

class pair : private Empty {
  Real second;
public:
// ... some accessors

};

Now in a templated version, we don't know in advance if the first type
will be empty (let us ignore the possibility that the second type may
be empty for now), so we dispatch based on is_empty<First>::value to
use the second implementation if it is empty and the first otherwise .

At least that's what I have seen in every implementation so far.
However, it seems to me that the second implementation should work
whether the type is empty or not, and one implementation is better
than two.

I am probably missing something here, could you tell me what are the
advantages of the first version when the type is not empty?

Try using the second implementation when Empty is an int, or a
function pointer.

-Howard
 
M

Marc

Howard said:
Try using the second implementation when Empty is an int, or a
function pointer.

Indeed, I should have just tried it. Derivation isn't likely to work
for those types :-(

Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top