Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make STL pair with one type an "empty struct" only take up the space of the other type?

I'm dealing with a templated key/value storage class that requires both a key and value type, and stores them internally as a std::pair. However, I found a case where I want to store only a key and still take advantage of this class's indexing. I would need to completely refactor this thing to deal with only a key and not a key/value pair (or waste lots of space), so I was wondering if there's a way to make a std::pair object take an empty struct (or something else), and only take up the same amount of space as the other type in the pair.

I tried it with this:

struct EmptyStruct
{
};

And ran this:

typedef std::pair<int, EmptyStruct> TestPair;
std::cout << sizeof(TestPair) << " vs " << sizeof(int) << "\n";

But got this output:

8 vs 4

In VC++ 2012 in "Release" mode with optimizations enabled, including /O1 "Minimize size".

Is there a way to make a struct be considered "sizeless" in the context of a std::pair?

like image 547
user173342 Avatar asked Jan 26 '26 03:01

user173342


2 Answers

You cannot do that with std::pair, but with Boost compressed_pair.

Before you set out to write your own fully-conforming pair template with compression, be aware that this is harder than it looks.

like image 189
pmr Avatar answered Jan 28 '26 16:01

pmr


Is there a way to make a struct be considered "sizeless" in the context of a std::pair?

No: because separate instances of a class must have distinct/distinguishable addresses ... so there's a minimum (non-zero) size.

like image 20
ChrisW Avatar answered Jan 28 '26 16:01

ChrisW