views:

401

answers:

3

Forgive my ignorance in asking this basic question but I've become so used to using Python where this sort of thing is trivial that I've completely forgotten how I would attempt this in C++.

I want to be able to pass a callback to a function that performs a slow process in the background, and have it called later when the process is complete. This callback could be a free function, a static function, or a member function. I'd also like to be able to inject some arbitrary arguments in there for context. (ie. Implementing a very poor man's coroutine, in a way.) On top of that, this function will always take a std::string, which is the output of the process. I don't mind if the position of this argument in the final callback parameter list is fixed.

I get the feeling that the answer will involve boost::bind and boost::function but I can't work out the precise invocations that would be necessary in order to create arbitrary callables (while currying them to just take a single string), store them in the background process, and invoke the callable correctly with the string parameter.

A: 

Sounds like you want to use the Observer pattern.

Konrad
I can't impose interface requirements on the objects that need notifying. The only requirement they can have is to have a function of the correct signature.
Kylotan
In fact, there's no guarantee that the thing I'll be calling back into is even an object at all. It could be a free function.
Kylotan
+7  A: 

The callback should be stored as a boost::function<void, std::string>. Then you can use boost::bind to "convert" any other function signature to such an object, by binding the other parameters.

Example

I've not tried to compile this, but it should show the general idea anyways

void DoLongOperation(boost::function<void, const std::string&> callback)
{
  std::string result = DoSomeLengthyStuff();
  callback(result);
}


void CompleteRoutine1(const std::string&);
void CompleteRoutine2(int param, const std::string&);

// Calling examples
DoLongOperation(&CompleteRoutine1); // Matches directly
DoLongOperation(boost::bind(&CompleteRoutine2, 7, _1)); // int parameter is bound to constant.

// This one is thanks to David Rodríguez comment below, but reformatted here:
struct S 
{ 
  void f( std::string const & );
};

int main() 
{ 
  S s;
  DoLongOperation( boost::bind( &S::f, &s, _1 ) ); 
}
Anders Abel
Could you provide an example? (Or a link to a specific example.) I already had a good idea that boost::function and boost::bind would do what I want but I have no clue about how to achieve that.
Kylotan
+1 and for a member function example: `struct S { void f( std::string const }; int main() { S s; DoLongOperation( boost::bind( }` where you can add extra arguments as you wish, just remember that `boost::bind` will copy the arguments.
David Rodríguez - dribeas
A: 

The easiest way:

class Callback
{
public:
  virtual ~Callback() {}
  virtual Callback* clone() const = 0;

  // Better to wrap the call (logging, try/catch, etc)
  void execute(const std::string& result) { this->executeImpl(result); }

protected:
  // Don't make sense to have them public
  Callback() {}
  Callback(const Callback&) {}
  Callback& operator=(const Callback&) { return *this; }

private:
  virtual void executeImpl(const std::string& result) = 0;
};

// Example
class Example: public Callback
{
public:
  Example(int a, int b): Callback(), mA(a), mB(b) {}
  virtual Example* clone() const { return new Example(*this); }

private:
  virtual void executeImpl(const std::string& result) {}

  int mA;
  int mB;
};

And then, you can pass the callback class (by pointer / reference) to the process. The class has a state, as required, and may be copied if necessary (if not, drop the clone).

Matthieu M.
Unfortunately this would seem to require deriving a new class from Callback for each call site that I have, which I'm definitely hoping to avoid.
Kylotan
Yes and no, you would only need one class per functionality, which does not seem unreasonable to me. After all, don't you already have one function per functionality ?
Matthieu M.
A typical use of a callback would be a one-liner - invoke the routine and pass the function you want it to call at the end. In a more complex situation it might be 2 or 3 lines (eg. of boost::bind) to convert from a member function to a free function or to add extra parameters. This is 10 or 11 lines, which is too unwieldly by comparison.
Kylotan
Yes, for one liner it can prove a bit unwieldy :) I thought you had full fledged callback in mind in which case a few more lines don't matter because they are an order less of magnitude in comparison to the body of the function itself.
Matthieu M.