c++ functor with weak reference

Started by
1 comment, last by Storyyeller 14 years, 1 month ago
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);
    }
};

I trust exceptions about as far as I can throw them.
Advertisement
... And what good do you think it will do to make such a thing?
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.
I trust exceptions about as far as I can throw them.

This topic is closed to new replies.

Advertisement