You can implement Finally
without type erasure and overhead of std::function
:
template
class Finally {
F f;
public:
template
Finally(Func&& func) : f(std::forward(func)) {}
~Finally() { f(); }
Finally(const Finally&) = delete;
Finally(Finally&&) = delete;
Finally& operator =(const Finally&) = delete;
Finally& operator =(Finally&&) = delete;
};
template
Finally make_finally(F&& f)
{
return { std::forward(f) };
}
And use it like:
auto&& doFinally = make_finally([&] { var++; });
Demo