-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy path365.md
72 lines (54 loc) · 1.79 KB
/
365.md
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
<details open><summary>Info</summary><p>
* **Did you know about C++26 static reflection proposal (5/N)?**
* https://wg21.link/P2996
</p></details><details open><summary>Example</summary><p>
```cpp
struct foo;
[[maybe_unused]] constexpr auto _ =
define_class(^foo, {std::meta::nsdm_description(^int, {.name = "bar"})});
foo f{.bar = 42}; // has bar int member
```
> https://godbolt.org/z/aqxanTe3r
</p></details><details open><summary>Puzzle</summary><p>
* **Can you implement template alias `pack` which will pack given struct by sorting members by their size?**
```cpp
template<class T> using pack; // TODO
struct unpacked {
short s;
int i;
bool b;
};
static_assert(12 == sizeof(unpacked));
using packed = pack<unpacked>;
static_assert(8 == sizeof(packed));
static_assert(requires(packed p) { p.i; p.s; p.b; });
```
> https://godbolt.org/z/hnPvsE9h3
</p></details>
</p></details><details><summary>Solutions</summary><p>
```cpp
namespace detail {
template<class T> struct packed;
template<class T> [[nodiscard]] consteval auto pack() {
std::vector members = std::meta::nonstatic_data_members_of(^T);
sort(members, [](auto lhs, auto rhs) consteval { return std::meta::size_of(lhs) < std::meta::size_of(rhs); });
std::vector<std::meta::nsdm_description> new_members{};
for (const auto& member: members) {
new_members.push_back({std::meta::type_of(member), {.name = std::meta::name_of(member)}});
}
return define_class(^packed<T>, new_members);
}
} // namespace detail
template<class T> using pack = [:detail::pack<T>():];
struct unpacked {
short s;
int i;
bool b;
};
static_assert(12 == sizeof(unpacked));
using packed = pack<unpacked>;
static_assert(8 == sizeof(packed));
static_assert(requires(packed p) { p.i; p.s; p.b; });
```
> https://godbolt.org/z/ExYfTv4nK
</p></details>