In our previous discussion, we explored a task-based while loop employing custom callables that passed copies of themselves to the next iteration, which follows the continuation-passing style used in the Parallel Patterns Library (PPL). In this session, we will implement the same function using a more traditional recursive approach, aiming to simplify the sharing of state between lambda callables in PPL-style programming.
On Writing Loops in PPL and Continuation-passing Style, Part 2
By Raymond Chen
From the article:
Last time, we came up with task-based
while
loop that involved creating a custom callable that passed copies of itself to the next iteration.This time, we’ll implement the function in terms of a more traditional recursion.
template<typename Callable> task<void> do_while_task( std::shared_ptr<Callable> const& f) { return (*f)().then([f](bool loop) { return loop ? do_while_task(f) : task_from_result(); }); } template<typename Callable, typename = std::enable_if_t<std::is_invocable_v<Callable>>> task<void> do_while_task(Callable&& callable) { using Decayed = std::decay_t<Callable>; return do_while_task( std::make_shared<Decayed>( std::forward<Callable>(callable))); }The real work happens in the first overload, which takes a ready-made
shared_ptr
. The second overload is a convenience method that lets you pass a callable, and it will wrap it in ashared_ptr
for you.
Add a Comment
Comments are closed.