-
Notifications
You must be signed in to change notification settings - Fork 2
/
dynamic_reassign.cpp
234 lines (187 loc) · 6.29 KB
/
dynamic_reassign.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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
Goal is to create an intermediate functor struct that can point to
lambdas including capture lambdas.
Then use that functor as a member functor that passes on its owner class
as a function argument to invoke the lambda it was pointed to
This is part of a tutorial series. Visit:
https://github.com/TheMaverickProgrammer/C-Python-Like-Class-Member-Decorators
*/
#include <iostream>
#include <memory>
#include <cassert>
#include <chrono>
#include <ctime>
#include <stdexcept>
#include <functional>
#include <type_traits>
#include <string>
#include <tuple>
using namespace std::placeholders;
using namespace std;
////////////////////////////////////
// weak optional value structure //
////////////////////////////////////
template<typename T>
struct optional_type {
T value;
bool OK;
bool BAD;
std::string msg;
// implicitly dissolve into value type T
operator T() {
return value;
}
optional_type(T t) : value(t) { OK = true; BAD = false; }
optional_type(bool ok, std::string msg="") : msg(msg) { OK = ok; BAD = !ok; }
};
/////////////////////////////////////
// decorators //
/////////////////////////////////////
// exception decorator for optional return types
template<typename F>
constexpr auto exception_fail_safe(F func) {
return [func](auto&&... args) {
using R = optional_type<decltype(func(args...))>;
try {
return R(func(args...));
} catch(std::iostream::failure& e) {
return R(false, e.what());
} catch(std::exception& e) {
return R(false, e.what());
} catch(...) {
// This ... catch clause will capture any exception thrown
return R(false, std::string("Exception caught: default exception"));
}
};
}
// this decorator can output our optional data
template<typename F>
constexpr auto output(F func) {
return [func](auto&&... args) {
auto value = func(args...);
auto opt = optional_type<decltype(value)>(value);
if(opt.BAD) {
std::cout << "There was an error: " << opt.msg << std::endl;
} else {
std::cout << "Bag cost $" << opt.value << std::endl;
}
return opt;
};
}
// this decorator prints time and returns value of inner function
// returning is purely conditional based on our needs, in this case
// we want to take advantage of the functional-like syntax we've created
template<typename F>
constexpr auto log_time(F func) {
return [func](auto&&... args) {
auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
auto opt = func(args...);
std::cout << "> Logged at " << std::ctime(&time) << std::endl;
return opt;
};
}
////////////////////////////////////
// visitor function //
////////////////////////////////////
template<typename F>
constexpr auto classmethod(F func) {
return [func](auto& a, auto&&... args) {
return (a.*func)(args...);
};
}
///////////////////////////////////////////////
// function traits //
///////////////////////////////////////////////
template<typename T>
struct function_traits;
// traits allows us to inspect type information from our function signature
template<typename R, typename Class, typename... Args>
struct function_traits<R (Class::*)(Args...)>
{
typedef R result_type;
using args_pack = std::tuple<Args...>;
};
template<typename R, typename... Args>
struct function_traits<std::function<R(Args...)>>
{
typedef R result_type;
using args_pack = std::tuple<Args...>;
};
// base-case definition
// we want to be able to digest a lambda function and member functions
template<typename ClassType, typename RType, typename ArgsPack>
class class_memberfunc;
// specialization for variadic arguments
template<typename ClassType, typename RType, typename... Args>
class class_memberfunc<ClassType, RType, std::tuple<Args...>> {
ClassType* self;
std::function<RType(ClassType&, Args...)> f;
public:
class_memberfunc(ClassType* self) : self(self) {
}
class_memberfunc(const class_memberfunc& rhs) {
this->self = rhs.self;
this->f = rhs.f;
}
std::function<RType(ClassType&, Args...)> operator*() {
return f;
}
template<typename F>
void operator=(const F& rhs) {
f = std::function<RType(ClassType&, Args...)>(rhs);
}
RType operator()(Args&&... args) {
return f(*self, args...);
}
};
// hide all the code-rewriting
template<typename Class>
class enable_memberfunc_traits {
protected:
/*
define our member functor alias
use function traits to deduce types
*/
template<typename Type>
using memberfunc = class_memberfunc<Class,
typename function_traits<Type>::result_type,
typename function_traits<Type>::args_pack>;
};
///////////////////////////////////////////////
// an example class with a member function //
///////////////////////////////////////////////
class apples : public enable_memberfunc_traits<apples> {
public:
// member function that throws
double calculate_cost_impl(int count, double weight) {
if(count <= 0)
throw std::runtime_error("must have 1 or more apples");
if(weight <= 0)
throw std::runtime_error("apples must weigh more than 0 ounces");
return count*weight*cost_per_apple;
}
double cost_per_apple;
// ctor
apples(double cost_per_apple) :
calculate_cost(this),
cost_per_apple(cost_per_apple) {
this->calculate_cost = &apples::calculate_cost_impl;
}
~apples() { }
// define a functor with the same signature as our member function
memberfunc<decltype(&apples::calculate_cost_impl)> calculate_cost;
};
////////////////////////////////////
// main //
////////////////////////////////////
int main() {
using namespace std;
apples groceries1(1.09);
std::cout << groceries1.calculate_cost(5, 3.34) << std::endl;
groceries1.calculate_cost = exception_fail_safe(classmethod(&apples::calculate_cost_impl));
groceries1.calculate_cost = log_time(output(*groceries1.calculate_cost));
std::cout << std::endl;
groceries1.calculate_cost(5, 3.34);
return 0;
}