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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With