Sign in to follow this  

c++ functor with weak reference

Recommended Posts

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;

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

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


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

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this