Hi all,
I'm on a project which uses a C++ compiler, but with a lot of C-isms. One of those is that there are objects with pairs of functions which allocate/deallocate resources. I don't have time to fix all of the design issues with the classes that do this (yet), but within one compilation unit I'd like to remove the chance for leaks.
So - if I wanted to use boost types to wrap around 2 functions f() and g(), where each function
- has a void or primitive return type
- takes zero or 1 argument
- where f() is called at some point in a scope, and then g() is called on exiting the scope from which f() is called and only if f() doesn't throw..
- has its return value ignored. [Gahh....]
Is there a boost::bind (or lambda) expression that I can wrap in a type?
I'm not adverse to using several template parameters.
If it were just nullary functions I could just use:
struct Reference {};
struct TypeWrapper{}; // Signify something like shared_ptr, a T which wraps around a pointer to an object of the type containing the functions, where T has a typedef value_type to refer to the wrapped type, and a get() to obtain a pointer to the wrapped pointer.
template<class T, type R1, type R2, class P = Reference>
struct ScopedDuals
{
typedef R1 (T::*f_t)();
typedef R2 (T::*g_t)();
ScopedDuals(T&t, f_t f, g_t g)
: t_(t), g_(g)
{
(t_.f)();
}
~ScopedDuals() { (t_.*g_)(); }
private:
T& t_;
g_t g_;
};
template<class T, type R1. type R2>
struct ScopedDuals<T, R1, R2, TypeWrapper>
{
typedef typname T::value_type Inner_t;
typedef R1 (Inner_t::*f_t)();
typedef R2 (Inner_t::*g_t)();
ScopedDuals(T&t, f_t f, g_t g)
: t_(t), g_(g)
{
(t_.get()->*f)();
}
~ScopedDuals() { (t_.get()->*g_)(); }
private:
T& t_;
g_t g_;
};
How do I generalize to include the possibility of a single argument?
and.... does anyone have a better suggestion for a name than "ScopedDuals"? While I think it's precise, it may not be useful to my teammates.
thanks,
Brian