1

I wanted to define a scopeguard, which runs some clean up code when scope exit. And I don't want to use std::function<void()> since it has some overhead. Then I come up with this implementation that is templated.

template <typename Fn>
class ScopeGuard {
public:
    ScopeGuard(Fn&& fn) : fn_(std::forward<T>(fn)) {}
    ~ScopeGuard() { fn_(); }
private:
    Fn fn_;
};

This works nicely for lambdas. However, it does not accept global functions, which are lvalues. How to solve this problem?

I think this is a more general question, how to make a template that can save any callable object (global functions, lambdas, class instance that has operator() with minimal overhead.

Is the following a better way?

template <typename Fn>
class ScopeGuard {
public:
    template <typename T>
    ScopeGuard(T&& fn) : fn_(std::forward<T>(fn)) {}
    ~ScopeGuard() {
        fn_();
    }
private:
    Fn fn_;
};
doraemon
  • 2,296
  • 1
  • 17
  • 36

1 Answers1

0

Actually the first implementation works for global functions as well - just use

ScopeGuard g(&foo);
muji4ok
  • 16