-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP394.Policy.cpp
More file actions
75 lines (70 loc) · 1.42 KB
/
Copy pathP394.Policy.cpp
File metadata and controls
75 lines (70 loc) · 1.42 KB
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
#include <iostream>
template<typename T>
struct AccumulationTraits;
template<>
struct AccumulationTraits<char>
{
using AccT = int;
static constexpr AccT zero = 0;
};
template<>
struct AccumulationTraits<short>
{
using AccT = int;
static constexpr AccT zero = 0;
};
template<>
struct AccumulationTraits<int>
{
using AccT = long;
static constexpr AccT zero = 0;
};
template<>
struct AccumulationTraits<unsigned int>
{
using AccT = unsigned long;
static constexpr AccT zero = 0;
};
template<>
struct AccumulationTraits<float>
{
using AccT = double;
static constexpr AccT zero = 0;
};
class SumPolicy
{
public:
template<typename T1, typename T2>
static void accumulate(T1& total, const T2& value)
{
total += value;
}
};
class MultPolicy
{
public:
template<typename T1, typename T2>
static void accumulate(T1& total, const T2& value)
{
total *= value;
}
};
template<typename T, typename Policy = SumPolicy, typename Traits = AccumulationTraits<T>>
auto accum(const T* beg, const T* end)
{
using AccT = typename Traits::AccT;
AccT res = Traits::zero;
while (beg != end)
{
Policy::accumulate(res, *beg);
beg++;
}
return res;
}
int main(int argc, char const *argv[])
{
int arr[3] = {1, 2, 3};
std::cout << accum(arr, arr+3) << std::endl;
std::cout << accum<int, MultPolicy>(arr, arr+3) << std::endl;
return 0;
}