c++functionclassmemberdesign-decisions

How can a function ask its caller class to invoke one of its methods?


I'm in a situation like this:

class Callee {
public:
  void request();
};

class Caller {
  void call() {
    Callee{}.request();
  }
  void invoke1(); // the implementation doesn't matter
  void invoke2(); // the implementation doesn't matter
  // more invoke()s
};

I want Callee::request() to request invocation of one of the Caller::invoke() member functions depending on the context which can be computed either in Callee::request() or in Caller::call():

void Callee::request() {
  // do stuff
  switch (context) {
    // request one of the invoke()s to be run immediately
  }
  // do more stuff
}

Which solutions would be elegant? I don't want (from most to least important):

It's OK if Callee::request() receives some arguments from the Caller.


Solution

  • There is a number of ways you can achieve this.