Search code examples
c++oopc++11callbackstd-function

Invoking member of an object from another one by using `std::function`


I'm trying to create a communication system between objects, in which a controller object keeps a vector of member functions of other objects, and calls/invokes them when needed.
I read several articles about usage of std::function, but I couldn't find one that covers this use case.

My code is:

#include <functional>
#include <Windows.h>

class Callable
{

};

class ClassA : public Callable
{
    public:
        double CallThis(double x, int y) const
        {
            MessageBoxW(NULL, L"CallThis() is called.", L"In ClassA", MB_ICONINFORMATION);
            return x + y;
        }
};

class ClassB : public Callable
{
    public:
        double CallMe(double x, int y) const
        {
            MessageBoxW(NULL, L"CallMe() is called.", L"In ClassB", MB_ICONINFORMATION);
            return x + y;
        }
};

class Caller
{
    public:
        void AddSubscriber( const Callable & ObjectToCall,
                            const std::function<double(const Callable &, double, int)> & Subscriber)
        {
            Subscribers.push_back(Subscriber);
            ObjectsToBeCalled.push_back(ObjectToCall);
        }
        void CallSubscribers()
        {
            for (size_t i=0; i<Subscribers.size(); i++)
            {
                Subscribers[i](ObjectsToBeCalled[i], 1.0, 2);
            }
        }
    private:
        std::vector<std::function<double(const Callable &, double, int)>> Subscribers;
        std::vector<const Callable &> ObjectsToBeCalled;
};

int APIENTRY wWinMain(  _In_        HINSTANCE   hInstance,
                        _In_opt_    HINSTANCE   hPrevInstance,
                        _In_        LPTSTR      lpCmdLine,
                        _In_        int         nCmdShow)
{
    // ...

    ClassA ObjectA;
    ClassB ObjectB;
    Caller ObjectCaller;
    ObjectCaller.AddSubscriber(ObjectA, &ClassA::CallThis);
    ObjectCaller.AddSubscriber(ObjectA, &ClassB::CallMe);
    Sleep(5000);
    ObjectCaller.CallSubscribers();

    // ...
}

The strange this is that, when I run this code I don't get any compiler errors in my own code, but I get errors from the STL files xmemory0 and vector. The errors are:

Error 1  xmemory0  527 error C2528: 'pointer' : pointer to reference is illegal
Error 2  xmemory0  528 error C2528: 'const_pointer' : pointer to reference is illegal
Error 3  xmemory0  561 error C2535: 'const Callable &(*std::allocator<_Ty>::address(const Callable &) throw() const)' : member function already defined or declared
Error 4  xmemory0  599 error C2528: '_Ptr' : pointer to reference is illegal
Error 5  xmemory0  604 error C2528: '_Ptr' : pointer to reference is illegal
Error 6  xmemory0  700 error C2528: 'pointer' : pointer to reference is illegal
Error 7  xmemory0  701 error C2528: 'const_pointer' : pointer to reference is illegal
Error 8  xmemory0  824 error C2535: 'const Callable &(*std::_Wrap_alloc<_Alloc>::address(const Callable &) const)' : member function already defined or declared
Error 9  xmemory0  890 error C2528: '_Ptr' : pointer to reference is illegal
Error 10 xmemory0  105 error C2528: 'abstract declarator' : pointer to reference is illegal
Error 11 xmemory0  107 error C2528: 'abstract declarator' : pointer to reference is illegal
Error 12 xmemory0  122 error C2528: 'pointer' : pointer to reference is illegal
Error 13 xmemory0  123 error C2528: 'const_pointer' : pointer to reference is illegal
Error 14 vector    773 error C2528: '_Pval' : pointer to reference is illegal
Error 15 vector   1184 error C2535: 'void std::vector<_Ty>::push_back(const Callable &)' : member function already defined or declared
Error 16 vector   1245 error C2535: 'std::_Vector_iterator<_Myvec> std::vector<_Ty>::insert(std::_Vector_const_iterator<_Myvec>,_Ty)' : member function already defined or declared
Error 17 vector   1494 error C2528: '_Ptr' : pointer to reference is illegal
Error 18 vector   1658 error C2528: '_Pval' : pointer to reference is illegal

What am I doing wrong? How do I make this code run?

(My IDE is Microsoft Visual Studio 2012.)


Solution

  • Looking at your code, it looks like you would be better off storing std::function<double(double, int)>, and then use std::bind to bind the objects to the member functions.

    template <typename F>
    void AddSubscriber( const Callable & obj,
                        F subscriber)
    {
        Subscribers.push_back(std::bind(subscriber, obj, _1, _2));
    }
    

    Or just de-couple Callable from Caller completely, by passing something convertible to std::function<double(double, int)> directly:

    class Caller 
    {
    public:
      template <typename F>
      void AddSubscriber(F&& subscriber)
      {
         subscribers.emplace_back(std::forward<F>(subscriber));
      }
      void CallSubscribers()
      {
          for (const auto& subscriber : subscribers)
          {
              subscriber(1.0, 2);
          }
      }
     private:
      std::vector<std::function<double(double, int)> subscribers;
    };
    

    and then do the binding from the caller side.

    Caller c;
    ClassA a;
    using namespace std::placeholders;
    c.AddSubscriber(std::bind(&ClassA::CallThis, a, _1, _2));