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:


Returning multiple values from a function:
* Using a Function Object Consumer

Table Of Contents
8 Arrays
11 Loops
39 Streams
42 Returning multiple values from a function
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype