Skip to content

Commit

Permalink
enhancement: Improve implementation of ExecuteOnScopeExit class (Open…
Browse files Browse the repository at this point in the history
  • Loading branch information
4kangjc authored May 4, 2023
1 parent 3998ba1 commit 66a2de6
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions src/pstd/include/pstd_defer.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ namespace pstd {
// // when f() exit, will print its running time.
// }
//

// CTAD: See https://en.cppreference.com/w/cpp/language/class_template_argument_deduction
#if __cpp_deduction_guides >= 201606

template <class F>
class ExecuteOnScopeExit {
public:
ExecuteOnScopeExit(F&& f) : func_(std::move(f)) {}
ExecuteOnScopeExit(const F& f) : func_(f) {}
~ExecuteOnScopeExit() { func_(); }

ExecuteOnScopeExit(const ExecuteOnScopeExit& e) = delete;
ExecuteOnScopeExit& operator=(const ExecuteOnScopeExit& f) = delete;

private:
F func_;
};

#else

class ExecuteOnScopeExit {
public:
ExecuteOnScopeExit() = default;
Expand All @@ -54,10 +74,8 @@ class ExecuteOnScopeExit {
ExecuteOnScopeExit(const ExecuteOnScopeExit& e) = delete;
void operator=(const ExecuteOnScopeExit& f) = delete;

template <typename F, typename... Args>
ExecuteOnScopeExit(F&& f, Args&&... args) {
func_ = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
}
template <typename F>
ExecuteOnScopeExit(F&& f) : func_(std::forward<F>(f)) {}

~ExecuteOnScopeExit() noexcept {
if (func_) func_();
Expand All @@ -67,6 +85,8 @@ class ExecuteOnScopeExit {
std::function<void()> func_;
};

#endif

} // namespace pstd

#define _CONCAT(a, b) a##b
Expand Down

0 comments on commit 66a2de6

Please sign in to comment.