forked from user1095108/generic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompose.hpp
125 lines (105 loc) · 2.45 KB
/
compose.hpp
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#ifndef COMPOSE_HPP
# define COMPOSE_HPP
# pragma once
#include <type_traits>
#include <utility>
namespace
{
template <typename R, typename ...A>
struct signature
{
};
template <typename R, typename ...A>
constexpr auto extract_signature(R (*const)(A...)) noexcept
{
return signature<R, A...>();
}
template <typename C, typename R, typename ...A>
constexpr auto extract_signature(R (C::* const)(A...)) noexcept
{
return signature<R, A...>();
}
template <typename C, typename R, typename ...A>
constexpr auto extract_signature(R (C::* const)(A...) const) noexcept
{
return signature<R, A...>();
}
template <typename F>
constexpr auto extract_signature(F const&) noexcept ->
decltype(&F::operator(), extract_signature(&F::operator()))
{
return extract_signature(&F::operator());
}
template <typename F1, typename F2, bool, typename ...A1>
class composer;
template <typename F1, typename F2, typename ...A1>
class composer<F1, F2, true, A1...>
{
F1 const f1_;
F2 const f2_;
public:
explicit composer(F1&& f1, F2&& f2) noexcept :
f1_(std::forward<F1>(f1)),
f2_(std::forward<F2>(f2))
{
}
auto operator()(A1&& ...args) const noexcept(
noexcept(f2_(f1_(std::forward<A1>(args)...)))
)
{
return f2_(f1_(std::forward<A1>(args)...));
}
};
template <typename F1, typename F2, typename ...A1>
class composer<F1, F2, false, A1...>
{
F1 const f1_;
F2 const f2_;
public:
explicit composer(F1&& f1, F2&& f2) noexcept :
f1_(std::forward<F1>(f1)),
f2_(std::forward<F2>(f2))
{
}
auto operator()(A1&& ...args) const noexcept(
noexcept(f1_(std::forward<A1>(args)...), f2_())
)
{
return f1_(std::forward<A1>(args)...), f2_();
}
};
template <
typename F1, typename R1, typename ...A1,
typename F2, typename R2, typename ...A2
>
inline auto compose(
F1&& f1, signature<R1, A1...> const,
F2&& f2, signature<R2, A2...> const) noexcept(
noexcept(
composer<F1, F2, sizeof...(A2), A1...>(std::forward<F1>(f1),
std::forward<F2>(f2)
)
)
)
{
return composer<F1, F2, sizeof...(A2), A1...>(std::forward<F1>(f1),
std::forward<F2>(f2)
);
}
}
template <typename F1, typename F2>
inline auto operator|(F1&& f1, F2&& f2) noexcept(
noexcept(
compose(
std::forward<F1>(f1), extract_signature(f1),
std::forward<F2>(f2), extract_signature(f2)
)
)
)
{
return compose(
std::forward<F1>(f1), extract_signature(f1),
std::forward<F2>(f2), extract_signature(f2)
);
}
#endif // COMPOSE_HPP