Debian Codegraph @

libstdc++-v3/testsuite/20_util/variant/visit.cc

raw
1 // Copyright (C) 2019-2025 Free Software Foundation, Inc.
2 //
3 // This file is part of the GNU ISO C++ Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
7 // any later version.
8
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // You should have received a copy of the GNU General Public License along
15 // with this library; see the file COPYING3. If not see
16 // <http://www.gnu.org/licenses/>.
17
18 // { dg-do run { target c++17 } }
19
20 #include <variant>
21 #include <functional> // reference_wrapper
22 #include <testsuite_hooks.h>
23
24 // N.B. there are more std::visit tests in ./compile.cc and ./run.cc
25
26 void
27 test01()
28 {
29 // Verify that visitation uses INVOKE and supports arbitrary callables.
30
31 struct X
32 {
33 int sum(int i) const { return i + n; }
34 int product(int i) const { return i * n; }
35 int n;
36 };
37
38 std::variant<X, X*, std::reference_wrapper<X>> vobj{X{1}};
39 int res = std::visit(&X::n, vobj);
40 VERIFY( res == 1 );
41
42 std::variant<int, short> varg{2};
43 res = std::visit(&X::sum, vobj, varg);
44 VERIFY( res == 3 );
45
46 X x{4};
47 vobj = &x;
48 res = std::visit(&X::n, vobj);
49 VERIFY( res == 4 );
50
51 varg.emplace<short>(5);
52 res = std::visit(&X::sum, vobj, varg);
53 VERIFY( res == 9 );
54
55 x.n = 6;
56 res = std::visit(&X::product, vobj, varg);
57 VERIFY( res == 30 );
58
59 vobj = std::ref(x);
60 x.n = 7;
61 res = std::visit(&X::n, vobj);
62 VERIFY( res == 7 );
63
64 res = std::visit(&X::product, vobj, varg);
65 VERIFY( res == 35 );
66 }
67
68 void
69 test02()
70 {
71 struct NoCopy
72 {
73 NoCopy() { }
74 NoCopy(const NoCopy&) = delete;
75 NoCopy(NoCopy&&) = delete;
76 ~NoCopy() { }
77
78 int operator()(int i) { return i; }
79 int operator()(const NoCopy&) { return 0; }
80 };
81
82 std::variant<NoCopy, int> v{1};
83 NoCopy f;
84 // Visit should not need arguments to be copyable:
85 int res = std::visit(f, v);
86 VERIFY( res == 1 );
87 v.emplace<NoCopy>();
88 res = std::visit(f, v);
89 VERIFY( res == 0 );
90 }
91
92 int
93 main()
94 {
95 test01();
96 test02();
97 }