Question

I am trying to implement Mediator Pattern in c++. I am trying to pass a member function address to another class`s (Mediator) function (SignOn), which keeps these callback functions in a vector, so that they can be invoked on all the Colleague objects.

But i am getting following error: "*error C2664: 'MediatorPattern::Mediator::SignOn' : cannot convert parameter 1 from 'void (__thiscall MediatorPattern::Colleague::* )(std::string &)' to 'MediatorPattern::Mediator::CallBack &'*"

My question is do it need to maintain a list of all colleague objects who are 'signed on', in Mediator object? Please help me about where i am getting wrong.

Here is the code:

namespace MediatorPattern
{

class Mediator;
class Colleague
{
    string _name;
    int _id;
    Mediator* p_myMediator;
    string _msg;
public:
    Colleague(Mediator *pMediator, string s, int id):_name(s), _id(id) 
    {
        p_myMediator = pMediator;
        _msg = "Hi ! I am " + _name;
    }
    void MyCallBack(string& msg_in /*message part from mediator*/)
    {
        cout<< _msg << msg_in<< endl;
    }
    void SubscribeBroadcast();  
};

class Mediator
{
    typedef void (Colleague::*CallBack)(const string& s);
    std::vector<CallBack> vecRecieverCallBack;
    //typedef std::vector<CallBack>::iterator VecIterator;

public:
    void SignOn(CallBack& callBack_in)
    {
        vecRecieverCallBack.push_back(callBack_in);
    }
    /*void Send(const string& s_in)
    {
        VecIterator it_begin = vecRecieverCallBack.begin();
        VecIterator it_end = vecRecieverCallBack.end();
        for(; it_begin != it_end; ++it_begin)
        {
        (*it_begin)(s_in);
        }
    }*/

};

void Colleague::SubscribeBroadcast()
{
    p_myMediator->SignOn(&Colleague::MyCallBack);
}

}
Was it helpful?

Solution

There are 2 errors:

  • Colleague::MyCallBack should take const string& instead of string&

  • and Mediator::SignOn should take CallBack callBack_in instead of CallBack&

    • the type CallBack defines a pointer to function, so variable / parameter of type CallBack needs to be initialized with an address of function (just like you do), but your SignOn as it is now takes a reference to CallBack (get rid of & there)

OTHER TIPS

You've got incompatible function signatures. Change the MyCallback to take a constant string reference, like so:

void MyCallBack(string const & msg_in)
//                     ^^^^^

Otherwise, change the definition of the Callback typedef.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top