Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a tuple and a compressed_pair?

Tags:

c++

tuples

boost

I've seen both used for the same purpose, but I wonder how the result would differ (if at all) and why this is used at all.

References to docs: compressed_pair and tuple.

like image 324
rubenvb Avatar asked Apr 24 '13 18:04

rubenvb


1 Answers

C++ requires all complete types to have a size greater than 0. If a type could have a size of 0, array indexing and other pointer math would go awry.

class EmptyClass { };

std::cout << sizeof( EmptyClass );  // Prints "1" (typically)

A boost::compressed_pair is a tuple of two elements doesn't require additional storage for one type that only has a size of 1 because a size of 0 is forbidden.

if ( sizeof( compressed_pair<int,EmptyClass> ) == sizeof(int) )
{
   std::cout << "EmptyClass was compressed.";  // (This will print)
}

This is achieved through Empty Base Optimization. Both types are put in a class wrapper, and if one type is "empty", that class becomes the parent of the other.

like image 92
Drew Dormann Avatar answered Sep 17 '22 20:09

Drew Dormann