Looks fine to me. To rein in the compile times a little bit, you can pull in
just the 0-argument version of function, e.g.,
#include // (not )
and use boost::function0<void> instead of boost::function<void>. Under MSVC,
you might even get fewer senseless ICEs :)
Oh, yes, function0 is enough. Thanks very much, Doug.
Well, could the copy constructing from a boost.bind result be avoided?
How about the following solution? Thanks.
#include
#include
#include
#define ON_BLOCK_EXIT(x) scoped_guard guard##__LINE__ = make_guard(::boost::bind##x);guard##__LINE__;
class scoped_guard_impl: ::boost::noncopyable
{
private:
typedef const ::boost::function0<void>& f_type;
bool dismissed_;
f_type f_;
public:
scoped_guard_impl(f_type v): f_(v), dismissed_(false) {}
~scoped_guard_impl() throw()
{
if(!dismissed_)
try {f_();}
catch(...) {}
}
void dismiss() throw() { dismissed_ = true; }
};
typedef scoped_guard_impl& scoped_guard;
typedef scoped_guard_impl make_guard;
#include
int main()
{
FILE* fp = fopen("hello.txt", "r");
ON_BLOCK_EXIT((fclose, fp));
//scoped_guard guard = make_guard(boost::bind(fclose, fp));
return 0;
}
Jon