Reputation: 14603
Is adding a callback parameter for the case when operation completes (also fails) a good programming practice? Example:
template <typename F>
void load(::std::string const& path, F&& f)
{
// after a long load
::std::invoke(f, path);
}
Here, f
might be invoked in the context of another thread. My question comes from pondering whether it would be worthwhile to have one-fire signal/slot pairs in a program. That is, a slot, that would be called only once. Otherwise, we might need to connect, then disconnect a signal, which could be considered tedious. The rationale is, that, with a return value, such as a bool value, we need to wait for the result, whereas, with a callback, we don't need to.
Upvotes: 1
Views: 134
Reputation: 1873
It's not bad practice in general. It's a fairly fundamental piece of asynchronous programming, as can be seen in Boost.Asio.
Boost.Asio uses almost that same syntax for all of its callback functions, except that it's C++03 and so it can't use invoke
. An example is async_read
, where the caller tells Asio to read from a socket and then call the callback function when finished, with the requirement (enforced via templates) that the callback function take in an error_code
as an argument that will be populated appropriately.
Upvotes: 2