• Advertisement
Sign in to follow this  

c++ functor with weak reference

This topic is 2901 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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;

    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 this post


Link to post
Share on other sites
Advertisement
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
Sign in to follow this  

  • Advertisement