Type-erased ScopeGuard
If you search online for a ScopeGuard example, you may chance upon an implementation that uses std::function
instead of a class template. The implementation itself is quite simple:
// Example 11 class ScopeGuard { public: template <typename Func> ScopeGuard(Func&& func) : func_(std::forward<Func>(func)) {} ~ScopeGuard() { if (!commit_) func_(); } void commit() const noexcept { commit_ = true; } ScopeGuard(ScopeGuard&& other) : commit_(other.commit_), func_(std::move(other.func_)) { other.commit(); } private: mutable bool commit_ = false; std::function<void()> func_; ScopeGuard& operator=(const ScopeGuard&) = delete; };
Note that this ScopeGuard is a class, not a class template. It has template constructors that can accept the...