Debian Codegraph @

documentation/manual/grammar/essence/demo.cc

raw
1 #include <iostream>
2
3 using namespace std;
4
5 struct SType
6 {
7 int x = 123;
8
9 template <typename Tp_>
10 inline SType &operator=(Tp_ &&rhs);
11 };
12
13 template <bool, typename Tp_>
14 struct Assign;
15
16 template <typename Tp_>
17 struct Assign<true, Tp_>
18 {
19 static SType &assign(SType *lhs, Tp_ &&tp);
20 };
21
22 template <typename Tp_>
23 struct Assign<false, Tp_>
24 {
25 static SType &assign(SType *lhs, Tp_ const &tp);
26 };
27
28 template <>
29 struct Assign<false, SType>
30 {
31 static SType &assign(SType *lhs, SType const &tp);
32 };
33
34 template <typename Tp_>
35 inline SType &Assign<true, Tp_>::assign(SType *lhs, Tp_ &&tp)
36 {
37 cout << "move assignment of some rhs type\n";
38 lhs->x = tp;
39 return *lhs;
40 }
41
42 template <typename Tp_>
43 inline SType &Assign<false, Tp_>::assign(SType *lhs, Tp_ const &tp)
44 {
45 cout << "std assign of some rhs type\n";
46 lhs->x = tp;
47 return *lhs;
48 }
49
50 inline SType &Assign<false, SType>::assign(SType *lhs, SType const &tp)
51 {
52 cout << "Assignment of Stype to Stype through copy-assignment\n";
53 lhs->x = tp.x;
54 return *lhs;
55 }
56
57 template <typename Tp_>
58 inline SType &SType::operator=(Tp_ &&rhs)
59 {
60 return Assign<
61 // the is_rvalue_reference is needed to set the first template
62 // param. true, resuling in move assignment, using the first
63 // overload:
64 // Assign<true, Tp_>::assign(SType *lhs, Tp_ &&tp)
65 std::is_rvalue_reference<Tp_ &&>::value,
66
67 // the rm ref. is needed to distinguish
68 // Assign<false, Tp_>::assign(SType *lhs, Tp_ const &tp) and
69 // Assign<false, SType>::assign(SType *lhs, SType const &tp)
70 typename std::remove_reference<Tp_>::type
71
72 >::assign(this, std::forward<Tp_>(rhs));
73 }
74
75 // ====================================================================
76
77 double fact()
78 {
79 return 3.14;
80 }
81
82 int main()
83 {
84 SType st;
85
86 int x = 10;
87
88 st = st;
89 cout << st.x << '\n';
90
91 st = x;
92 cout << st.x << '\n';
93
94
95 st = int(5);
96 cout << st.x << '\n';
97
98 st = fact();
99 cout << st.x << '\n';
100 }
101
102
103