使用函式物件使用者

我們可以提供將使用多個相關值呼叫的消費者:

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 中編寫。