Search code examples
c++boostboost-bind

Boost::bind with object placeholder


I am trying to implement the observer pattern with the catch that I need to add new functionality into each observer later on in the project.

class Obsevers {
public:
    virtual ~Obsevers() {}
};

class TestObserver : public Obsevers {
public:
    void print1(int i) {
        std::cout << i << std::endl;
    }
};

class TestObserver2 : public Obsevers {
public:
    void print2(int i, char c) {
        std::cout << i << " , " << c << std::endl;
    }
    //possible new functions here later
};

My notify method is as follows:

template<typename Type, typename Notify>
void NotifyObserver(Notify notify) {
    typedef std::list<Obsevers*>::iterator iter;
    iter it = m_observers.begin();
    iter end = m_observers.end();
    for(; it != end; ++it) {
        Type * o = dynamic_cast<Type*>(*it);
        if(o == NULL) continue;
        notify(o);
    }
}

To make a call to notify the code is as follows.

NotifyObserver<TestObserver2>(boost::bind(&TestObserver2::print2, _1, 32, 'b'));

Now given the context with the above blocks of code my question is using a placeholder(_1) for the object parameter in bind correct or is this undefined behavior?

The boost documentation on bind did no specify using a placeholder for objects only for function parameters.


Solution

  • Your code is correct.

    The Boost.Bind documentation indicates that your code

    boost::bind(&TestObserver2::print2, _1, 32, 'b')

    is the same as

    boost::bind<void>(boost::mem_fn(&TestObserver2::print2), _1, 32, 'b')

    where boost::mem_fn is responsible for invoking the pointer-to-member-function. As long as the bound object is evaulated with something that boost::mem_fn can use, such as a pointer or reference, it will properly invoke the function.