Design question: asynchronous API in C++
I want to provide an asynchronous C++ API. I.e. placing a request will
not immediately provide a reply. Instead a callback signals the
availability of the result.
The classic solution is to provide an interface that must be implemented
by a class of the caller. This interface contains a method for the
Advantage: the implementing classes could also be used to track the
state of the request. (In this case it is an abstract base class rather
than an interface.)
// Notify availability of result.
virtual void OnCompleteion() = 0;
// Cancel an outstanding request.
// Do not call OnCompletion once it returns.
// Fetch the result data (and wait if necessary).
// If called from OnCompletion() the returned data must not be used
// after OnCompletion returned.
// If /not/ called from OnCompletion the lifetime of Result is
// extended until this class instance dies.
const Result& ReceiveResult();
Unfortunately this is very bulky, because the caller has to implement
one class for each different call. So I would like to have a more
The requirements are:
- 1. The caller places a request, does some other processing and then
waits for the reply.
- 2. The caller places a request and gets notified as soon as the reply
- 3. The caller places a request with fire and forget.
Case 2 is the most important one. Whether the notification function
already receives the reply as parameters is optional. An additional call
to a method of the tracking object that is returned when placing the
request is also fine.
In fact the returned data could be rather large and a value copy should
Has anyone an idea that comes with less effort for the caller? I would
prefer something with template meta programming and preferably no more
than two code lines for each call.
I think that Lambda expressions would help. However, my compiler does
not support them.