Debian Codegraph @

yo/advancedtemplates/examples/exprtempl.cc

raw
1 #include <iostream>
2 #include <vector>
3 #include <functional>
4
5 using namespace std;
6
7 template<typename LHS, typename RHS, template<typename> class Operation>
8 struct BinExpr;
9
10 template<typename RHS>
11 struct BasicType
12 {
13 using ObjType = RHS;
14 };
15
16 template<typename LHS, typename RHS, template<typename> class Operation>
17 struct BasicType<BinExpr<LHS, RHS, Operation>>
18 {
19 using ObjType = typename BinExpr<LHS, RHS, Operation>::ObjType;
20 };
21
22 template<typename LHS, typename RHS, template <typename> class Operation>
23 struct BinExpr
24 {
25 using ObjType = typename BasicType<RHS>::ObjType;
26 using value_type = typename ObjType::value_type;
27
28 LHS const &d_lhs;
29 RHS const &d_rhs;
30
31 BinExpr(LHS const &lhs, RHS const &rhs)
32 :
33 d_lhs(lhs),
34 d_rhs(rhs)
35 {}
36
37 size_t size() const
38 {
39 return d_lhs.size();
40 }
41
42 value_type operator[](size_t ix) const
43 {
44 static Operation<value_type> operation;
45 return operation(d_lhs[ix], d_rhs[ix]);
46 }
47
48 operator ObjType() const
49 {
50 ObjType retVal;
51 for (size_t ix = 0; ix != d_lhs.size(); ++ix)
52 retVal.push_back((*this)[ix]);
53 return retVal;
54 }
55 };
56
57 template<typename LHS, typename RHS>
58 BinExpr<LHS, RHS, plus> operator+(LHS const &lhs, RHS const &rhs)
59 {
60 return BinExpr<LHS, RHS, plus>(lhs, rhs);
61 }
62
63 int main()
64 {
65 vector<int> one {1, 2, 3};
66 vector<int> two {4, 5, 6};
67
68 vector<int> three = one + two + (one + two);
69
70 auto four = one + two + (one + two);
71
72 auto z = "hello world";
73
74 cout << z << '\n';
75
76 cout << three[0] << ' ' << three[2] << '\n';
77 cout << four[0] << ' ' << four[2] << '\n';
78 }