blob: 8186e6bf0764bd10629252623b7b4df4b8823e82 (
plain) (
blame)
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
|
#if 0
set -xe
g++ -std=c++20 -fsyntax-only cond_trivial_destr.cc
clang++ -std=c++20 -fsyntax-only cond_trivial_destr.cc
exit 0
#endif
#include <type_traits>
// Conditional trivial destructible.
//
// Since destructors can't have template parameters, std::enable_if can't be
// used to selectively enable or disable the destructor via SFINAE.
//
// If a template class wants to be trivially destructible depending on the
// template parameter, one has to work around it with some template
// specialization (pre cpp20). The implementation in the namespace v1 gives an
// example for that.
//
// Starting with cpp20 we can leverage concepts to enable / disable different
// destructor implementations. The implementations in the namespace v2 gives an
// example for that.
// -- PRE CPP20 ----------------------------------------------------------------
namespace v1 {
template <typename T, bool = std::is_trivially_destructible_v<T>>
struct storage {
~storage() {
if (has_val) {
val.~T();
has_val = false;
}
}
union {
T val;
};
bool has_val = false;
};
template <typename T>
struct storage<T, true> {
union {
T val;
};
};
template <typename T>
struct option : private storage<T> {};
} // namespace v1
// -- SINCE CPP20 --------------------------------------------------------------
namespace v2 {
#if __cplusplus >= 202002L
template <typename T>
struct option {
~option() = default;
~option()
requires(!std::is_trivially_destructible_v<T>)
{
val.~T();
}
private:
union {
T val;
};
bool has_value = false;
};
#endif
} // namespace v2
// -- TESTEE -------------------------------------------------------------------
struct trivial {};
static_assert(std::is_trivially_destructible_v<trivial>, "");
struct non_trivial {
~non_trivial() {
}
};
static_assert(!std::is_trivially_destructible_v<non_trivial>, "");
// -- TEST ---------------------------------------------------------------------
static_assert(std::is_trivially_destructible_v<v1::option<trivial>>, "");
static_assert(!std::is_trivially_destructible_v<v1::option<non_trivial>>, "");
#if __cplusplus >= 202002L
static_assert(std::is_trivially_destructible_v<v2::option<trivial>>, "");
static_assert(!std::is_trivially_destructible_v<v2::option<non_trivial>>, "");
#endif
|