Debian Codegraph @

gcc/testsuite/g++.dg/cpp23/explicit-obj-lambda3.C

raw
1 // P0847R7
2 // { dg-do run { target c++23 } }
3
4 // an adaptation of one of the examples in P0847R7
5
6 struct Leaf { };
7 struct Node;
8
9 struct Tree {
10 enum class stored {leaf, node};
11 stored _discriminator;
12 union {
13 Leaf _leaf;
14 Node* _node;
15 };
16 Tree(Leaf) : _discriminator(stored::leaf), _leaf() {}
17 Tree(Node& node) : _discriminator(stored::node), _node(&node) {}
18 };
19
20 struct Node {
21 Tree left;
22 Tree right;
23 };
24
25 template<typename Visitor>
26 auto visit_tree(Visitor&& visitor, Tree const& tree)
27 {
28 switch (tree._discriminator)
29 {
30 case Tree::stored::leaf:
31 return visitor (tree._leaf);
32 case Tree::stored::node:
33 return visitor (tree._node);
34 default:
35 __builtin_abort ();
36 }
37 }
38
39 template<typename... Ts>
40 struct overload : Ts... { using Ts::operator()...; };
41
42 int main()
43 {
44 static constexpr int true_num_leaves = 8;
45 Node branch0{.left = Leaf{}, .right = Leaf{}};
46 Node branch1{.left = Leaf{}, .right = branch0};
47 Node branch2{.left = Leaf{}, .right = Leaf{}};
48 Node branch3{.left = branch1, .right = branch2};
49 Node branch4{.left = branch3, .right = Leaf{}};
50 Node branch5{.left = Leaf{}, .right = Leaf{}};
51 Node branch6{.left = branch4, .right = branch5};
52
53 Tree root (branch6);
54
55 int num_leaves = visit_tree (overload{
56 [](Leaf const&) { return 1; },
57 [](this auto const& self, Node* n) -> int {
58 return visit_tree (self, n->left) + visit_tree (self, n->right);
59 }},
60 root);
61 if (num_leaves != true_num_leaves)
62 __builtin_abort ();
63 }
64