C++ finalizer template Consider, please, my code of the finalizer template:

#include &lt;functional&gt;


template&lt;typename F, typename... Args&gt;
class finally
{
public:

  finally(F action, const Args&amp;... args) :
      _action(std::bind(action, args...))
  {}
  ~finally()
  {
    if(enabled)
      _action();
  }

  bool enabled = true;

private:

  std::function&lt;void()&gt; _action;
};


In particular I would enhance this template to avoid of using a typenames twice. Let's say we need to close some file on leaving some block of code. Then we declare an object:

finally&lt;int(int), int&gt; f(close, some_file);


Here I used the standard close function as an action. But I should use int twice in the &lt;int(**int**), **int**&gt;. Is there any way to avoid this?
You can avoid specifying argument types twice by employing a constructor template:

template&lt;typename F&gt;
class finally
{
public:
  template&lt;typename... Args&gt;
  finally&lt;F&gt;(F action, const Args&amp;... args) { /* business as usual */ }
  ...
};


But that's not everything. The std::bind's arguments are either copied or moved, they are never passed by reference. Thus, despite const Args&amp;... args, you might end up copying your arguments.

To void this issue, consider using perfect forwarding (as well as ditching std::bind):

template&lt;typename... Args&gt;
finally&lt;F&gt;(F action, Args&amp;&amp;... args) :
    _action([action, &amp;args...]{ action(std::forward&lt;Args&gt;(args)...); }) {}


Another thing worth considering is the exception safety of action. Since you're invoking it in a destructor, you're risking facing std::terminate if it throws. A small try block will fix it. Also, as of now, enabled seems redundant.

And yes, even with all these fixes, the semantics of finally seems rather unpleasant compared to more traditional scope guards. At least to me.

Edit: full code - https://ideone.com/iThn0i