1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
#include <algorithm>
#if 0
set -xe
g++ -std=c++17 -fsyntax-only compressed_pair.cc
clang++ -std=c++17 -fsyntax-only compressed_pair.cc
g++ -std=c++20 -fsyntax-only compressed_pair.cc
clang++ -std=c++20 -fsyntax-only compressed_pair.cc
exit 0
#endif
#include <type_traits>
// Minimal compressed pair implementation.
//
// In cpp even if a class is zero-sized, adding a member of such a class,
// allocates 1 byte in the layout of the instantiating class. In generic
// programming one sometimes wants to store a member of a template argument and
// in the best case for zero-sized template types one does not want to pay a
// price.
//
// One example for this is std::unique_ptr with a custom state-less deleter:
//
#include <memory>
struct freer {
void operator()(void* p) {
std::free(p);
}
};
std::unique_ptr<char, freer> ptr{nullptr};
static_assert(sizeof(ptr) == sizeof(char*), "");
//
// Before cpp20 this can be achieved with some template specialization tricks
// and deriving from the type if it is not empty and not final.
//
// Starting with cpp20 the [[no_unique_address]] attribute [1] was added which
// allows the compiler to not allocate space in the layout of a class for a
// given member if that is zero-sized.
//
// [1] https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
namespace cpp11 {
template <typename T, int Idx, bool = std::is_empty_v<T> && !std::is_final_v<T>>
struct entry {
T& get() {
return val;
}
T val;
};
template <typename T, int Idx>
struct entry<T, Idx, true> : T {
T& get() {
return *static_cast<T*>(this);
}
};
template <typename T, typename U>
struct pair : entry<T, 0>, entry<U, 1> {
T& first() {
return static_cast<entry<T, 0>*>(this)->get();
}
U& second() {
return static_cast<entry<U, 1>*>(this)->get();
}
};
} // namespace cpp11
struct empty {};
#if __cplusplus >= 202002L
namespace cpp20 {
template <typename T, typename U>
struct pair {
T& first() {
return m_first;
}
U& second() {
return m_second;
}
[[no_unique_address]] T m_first;
[[no_unique_address]] U m_second;
};
} // namespace cpp20
#endif
// -- TEST ME ------------------------------------------------------------------
static_assert(sizeof(cpp11::pair<int, int>) == 8);
static_assert(sizeof(cpp11::pair<int, empty>) == 4);
static_assert(sizeof(cpp11::pair<empty, empty>) == 2);
#if __cplusplus >= 202002L
static_assert(sizeof(cpp20::pair<int, int>) == 8);
static_assert(sizeof(cpp20::pair<int, empty>) == 4);
static_assert(sizeof(cpp20::pair<empty, empty>) == 2);
#endif
|