Wednesday, September 12, 2012

Here is some code I just wrote. I think it's brilliant. I need to think over it a bit more to make it easier but I'm pretty happy with it so I decided to post it here.

*Disclaimer* I am definitely not going to be the first person to think of this:


template <typename ctorType, typename dtorType>
class RiaaWrapper
{
public:
RiaaWrapper(ctorType inCtor, dtorType inDtor)
: _inCtor(inCtor)
, _inDtor(inDtor)
{
_inCtor();
}
~RiaaWrapper()
{
_inDtor();
}
private:
ctorType _inCtor;
dtorType _inDtor;
};
You use it like this:


class AutoMutex2 : public RiaaWrapper<std::function<TTV_ErrorCode()>,  std::function<TTV_ErrorCode()> >
{
public:
AutoMutex2(ttv::Mutex* m)
: RiaaWrapper<std::function<TTV_ErrorCode()>,  std::function<TTV_ErrorCode()> >
(std::bind(&ttv::Mutex::Lock, m, ttv::WAIT_INFINITE),
std::bind(&ttv::Mutex::Unlock, m))
{

}
};
And you can ofcourse use it for any class/pair of functions you want to call.