Hello to all, how to declare a member function that accepts functor of other class ?
Thanks.
Printable View
Hello to all, how to declare a member function that accepts functor of other class ?
Thanks.
You err... declare the member function to take an object of that other class as an argument.
The typical way to make a function take an arbitrary functor as opposed to a specific type is to use templates. The downside, of course, is that the definition must be inline.
An alternative is to use std::function (which is available as boost::function prior to C++1x). This is actually necessary if you intend to store the functor somewhere.
Thanks for the reply.
The purpose of my program to use functor as argument of function is to achieve callback mechanism. I wonder whether my callback mechanism is correct in the method of attach() and notify().
Code:class subject
{
public:
typedef std::vector<observer*>::iterator vecIte;
public:
subject();
virtual ~subject();
// Take functor
void attach(observer*);
void detach(observer*);
// Take generalize functor
// 1. Template function
// 2. boost::function
void notify();
void setValue(int);
int getValue();
void calculate();
private:
std::vector<observer*> cont;
int value;
};
// ==================
void subject::attach(observer* anObs)
{
vecIte myIte = find(cont.begin(), cont.end(),
anObs);
if (myIte == cont.end())
{
cont.push_back(anObs);
}
}
// ==================
void subject::notify()
{
myForeach(observer* anObs, cont)
{
anObs->operator()(this);
}
}
// ==================
int main()
{
observer anObs;
subject sub;
sub.attach(&anObs);
sub.calculate();
return 0;
}
Please comment it.
What is boost::function ?
AFAIK, it is a functor wrapper but what is the usage of boost::function ?
I'm not sure that you want a functor here. I have usually seen multiple inheritance as a way of solving this. Create an interface class called EventHandler which provides a pure virtual function called processEvent. All observers must inherit from this interface and register with an event supplier. Of course it is possible that it is the only base class needed for some. The point is that an observer could implement any number of interfaces with multiple inheritance. In your case the Observer class could be the event handler and the call back function name can be whatever you wish. You can use dynamic_cast to ensure that the event handler objects implement the observer interface. I'm not sure what your myForeach is supposed to be. If you have a container of pointers you can use std::for_each and create a functor that calls processEvent on each object since you have a container of observers that provides iterator support.