Commit 238331fe authored by Dominik Charousset's avatar Dominik Charousset

Use scope guard in custom type example 3

parent a2ea6a22
// Showcases custom message types that cannot provide // Showcases custom message types that cannot provide
// friend access to the inspect() function. // friend access to the inspect() function.
// Manual refs: 20-49, 51-76 (TypeInspection) // Manual refs: 20-49, 76-103 (TypeInspection)
#include <utility> #include <utility>
#include <iostream> #include <iostream>
...@@ -48,6 +48,31 @@ private: ...@@ -48,6 +48,31 @@ private:
int b_; int b_;
}; };
// A lightweight scope guard implementation.
template <class Fun>
class scope_guard {
public:
scope_guard(Fun f) : fun_(std::move(f)), enabled_(true) { }
scope_guard(scope_guard&& x) : fun_(std::move(x.fun_)), enabled_(x.enabled_) {
x.enabled_ = false;
}
~scope_guard() {
if (enabled_) fun_();
}
private:
Fun fun_;
bool enabled_;
};
// Creates a guard that executes `f` as soon as it goes out of scope.
template <class Fun>
scope_guard<Fun> make_scope_guard(Fun f) {
return {std::move(f)};
}
template <class Inspector> template <class Inspector>
typename std::enable_if<Inspector::is_saving::value, typename std::enable_if<Inspector::is_saving::value,
typename Inspector::result_type>::type typename Inspector::result_type>::type
...@@ -59,20 +84,14 @@ template <class Inspector> ...@@ -59,20 +84,14 @@ template <class Inspector>
typename std::enable_if<Inspector::is_loading::value, typename std::enable_if<Inspector::is_loading::value,
typename Inspector::result_type>::type typename Inspector::result_type>::type
inspect(Inspector& f, foo& x) { inspect(Inspector& f, foo& x) {
struct tmp_t {
tmp_t(foo& ref) : x_(ref) {
// nop
}
~tmp_t() {
// write back to x at scope exit
x_.set_a(a);
x_.set_b(b);
}
foo& x_;
int a; int a;
int b; int b;
} tmp{x}; // write back to x at scope exit
return f(meta::type_name("foo"), tmp.a, tmp.b); auto g = make_scope_guard([&] {
x.set_a(a);
x.set_b(b);
});
return f(meta::type_name("foo"), a, b);
} }
behavior testee(event_based_actor* self) { behavior testee(event_based_actor* self) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment