Debian Codegraph @

yo/advancedtemplates/examples/exprtempl6.cc

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