-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaccumulator_map.cpp
99 lines (85 loc) · 1.92 KB
/
accumulator_map.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <cmath>
#include <functional>
enum Operation
{
SUM = 0,
MULTI,
DIV,
SUBSTR,
EXP
};
class Calculator
{
public:
Calculator() : m_func( [](double a, double b) -> double { return a;} )
{}
Calculator& operator[](Operation op)
{
switch (op)
{
case SUM:
m_func = [](double a, double b) -> double { return a + b;};
break;
case MULTI:
m_func = [](double a, double b) -> double { return a * b;};
break;
case DIV:
m_func = [](double a, double b) -> double { return a / b;};
break;
case SUBSTR:
m_func = [](double a, double b) -> double { return a - b;};
break;
case EXP:
m_func = pow;
break;
default:
break;
}
return *this;
}
double calculate(double val1, double val2)
{
return m_func(val1, val2);
}
private:
std::function<double(double, double)> m_func;
};
class AccumulatorMap
{
public:
AccumulatorMap() = delete;
explicit AccumulatorMap(double initialValue) : m_value(initialValue)
{}
AccumulatorMap& operator()(Operation op, double value)
{
m_value = m_calc[op].calculate(m_value, value);
return *this;
}
operator double()
{
return m_value;
}
private:
double m_value;
Calculator m_calc;
};
double CircleArea(double radius)
{
return AccumulatorMap(radius)
(EXP, 2)
(MULTI, 3.14);
}
double SphereVolume(double radius)
{
return AccumulatorMap(radius)
(EXP, 3)
(MULTI, 4)
(DIV, 3)
(MULTI, 3.14);
}
int main()
{
double value1 = CircleArea(4);
double value2 = SphereVolume(7);
return 0;
}