Debian Codegraph @

yo/advancedtemplates/examples/exprtempl4.cc

raw
1 #include <iostream>
2 #include <vector>
3 #include <functional>
4
5 using namespace std;
6
7 template <typename Type>
8 struct Adder
9 {
10 Type operator()(Type const &lhs, Type const &rhs) const
11 {
12 return lhs + rhs;
13 }
14 };
15
16
17 template<typename LHS, typename RHS, template<typename> class Operation>
18 struct BinExpr;
19
20 template<typename Type>
21 struct BasicType
22 {
23 using ObjType = Type;
24 };
25
26 template<typename LHS, typename RHS, template<typename> class Operation>
27 struct BasicType<BinExpr<LHS, RHS, Operation>>
28 {
29 using ObjType = typename BinExpr<LHS, RHS, Operation>::ObjType;
30 };
31
32 template<typename LHS, typename RHS, template <typename> class Operation>
33 struct BinExpr
34 {
35 using ObjType = typename BasicType<RHS>::ObjType;
36 using value_type = typename ObjType::value_type;
37
38 LHS const &d_lhs;
39 RHS const &d_rhs;
40
41 BinExpr(LHS const &lhs, RHS const &rhs)
42 :
43 d_lhs(lhs),
44 d_rhs(rhs)
45 {}
46
47 size_t size() const
48 {
49 return d_lhs.size();
50 }
51
52 value_type operator[](size_t ix) const
53 {
54 static Operation<value_type> operation;
55
56 return operation(d_lhs[ix], d_rhs[ix]);
57 }
58
59 operator ObjType() const
60 {
61 ObjType retVal;
62
63 retVal.resize(size());
64
65 retVal.reserve(size());
66
67 for (size_t ix = 0, end = size(); ix != end; ++ix)
68 new(&retVal[ix]) value_type{ (*this)[ix] };
69
70 return retVal;
71 }
72 };
73
74 template<typename LHS, typename RHS>
75 BinExpr<LHS, RHS, Adder> operator+(LHS const &lhs, RHS const &rhs)
76 {
77 return BinExpr<LHS, RHS, Adder>(lhs, rhs);
78 }
79
80 struct VI: public vector<int>
81 {
82 static size_t const s_max = 10000;
83
84
85 VI()
86 :
87 vector<int>(s_max, 1)
88 {}
89 };
90
91 int main(int argc, char **argv)
92 {
93 if (argc == 1)
94 {
95 cout << "arg1: number of iterations\n";
96 return 0;
97 }
98
99 VI a, b, c, d;
100
101 for (size_t idx = 0, count = stoul(argv[1]); idx != count; ++idx)
102 d = a + b + c + d + a + b + c + d;
103
104 cout << d.front() << ", " << d.back() << '\n';
105 }