0

I am creating an MVC application and I want a way for the model to be able to send output text to the GUI to be displayed.

A few people have recommended function pointers but I have now learned that if you pass a function pointer of a member function you also have to pass a pointer to the object (why not just pass the object pointer only so methods can be called on it?)

Anyway, I have also been recommended to use boost::signals2. I have implemented a very simple working example. I basically bind the signal to a function of the GUI object. Then pass a pointer to the signal to an object that can trigger the signal. See code below...

struct GUI
{
    void talk()
    {
        cout << "hello" << endl;
    }
};

class Person {
public:
    Person(){}
    Person(const signal<void ()>* sig) : sig(sig){}
    virtual ~Person(){}

    void testSig()
    {
       (*sig)();
    }


private:
    const signal<void ()>* sig;
};

int main() {
    boost::signals2::signal<void ()> sig;
    GUI gui;
    sig.boost::signals2::connect(boost::bind(&GUI::talk, &gui));

    Person tom(&sig);
    tom.testSig();
}

As I am a total beginner with signals I am not entirely sure if I am using them as they are intended to be used.

Armada
  • 718
  • 8
  • 19

1 Answers1

4

Why don't you put signal inside the person class? You could do something like this:

struct GUI
{
    void talk() {
        cout << "hello" << endl;
    }
};

class Person {
    boost::signals2::signal<void ()> sig_;
public:
    Person() {}
    virtual ~Person() {}

    template <typename F>
    void connect(F f) {
        sig_.connect(f);
    }

    void testSig() {
       sig_();
    }
};

int main()
{
    GUI gui;
    Person tom;

    tom.connect(boost::bind(&GUI::talk, &gui));
    tom.testSig();
}
Grigorii Chudnov
  • 3,046
  • 1
  • 25
  • 23