使用函数对象使用者

我们可以提供将使用多个相关值调用的消费者:

Version >= C++ 11

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';
});

这被称为 延续传递风格

你可以通过以下方式调整将元组返回到延续传递样式函数的函数:

Version >= C++ 17

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';
};

更复杂的版本可以在 C++ 14 或 C++ 11 中编写。