# c++ functor with weak reference

## Recommended Posts

Storyyeller    215
First off, is there any easy way to make a functor that calls a member function of an object with a weak reference? Here's my attempt. The problem is that it assumes a void function taking no arguments. Is there anyway to make a more generic version that can operate on any member function?
#pragma once

#include "BOOST/shared_ptr.hpp"
#include "BOOST/weak_ptr.hpp"
#include "BOOST/function.hpp"

template <class T>
class WeakFunctor
{
typedef boost::shared_ptr<T> t_sptr;
typedef boost::weak_ptr<T> t_wptr;
typedef boost::function<void (T*)> voidfunct;

t_wptr myobject;
voidfunct myfunc;

public:
WeakFunctor( t_wptr object, voidfunct memfunc )
:myobject(object), myfunc(memfunc) {}

void operator ()()
{
t_sptr lockedobject = myobject.lock();

if(lockedobject)
{
myfunc(lockedobject.get());
}
}

static boost::function<void ()> CreateWeakFunctor( t_wptr object, voidfunct memfunc )
{
return WeakFunctor(object, memfunc);
}
};



##### Share on other sites
Zahlman    1682
... And what good do you think it will do to make such a thing?

##### Share on other sites
Storyyeller    215
Well I can't imagine any other way to safely have callbacks to an object with indeterminate lifetime.

Although Boost Lambda looks promising, so I might be able to use that to do the same thing.