Using a Function Object Consumer

suggest change

We can provide a consumer that will be called with the multiple relevant values:

template <class F>
void foo(int a, int b, F consumer) {
    consumer(a + b, a - b, a * b, a / b);
}

// use is simple... ignoring some results is possible as well
foo(5, 12, [](int sum, int , int , int ){
    std::cout << "sum is " << sum << '\n';
});

This is known as “continuation passing style”.

You can adapt a function returning a tuple into a continuation passing style function via:

template<class Tuple>
struct continuation {
  Tuple t;
  template<class F>
  decltype(auto) operator->*(F&& f)&&{
    return std::apply( std::forward<F>(f), std::move(t) );
  }
};
std::tuple<int,int,int,int> foo(int a, int b);

continuation(foo(5,12))->*[](int sum, auto&&...) {
  std::cout << "sum is " << sum << '\n';
};

with more complex versions being writable in C++14 or C++11.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents