この記事は、C++ (fork) Advent Calendar 2013の15日目です。


C++14規格レビュー勉強会#2で話に出した、future::thenの値が渡されるバージョンを書いてみました。ただし、自由関数(グローバル関数)で、仮にthen_by_valueという名前にしています。

// GCC 4.8.2, Boost 1.55
#define BOOST_THREAD_VERSION 4
#include <iostream>
#include <string>
#include <functional>
#include <boost/thread/future.hpp>
 
template<typename T, typename F>
boost::future<typename std::result_of<F (T)>::type>
then_by_value(boost::future<T>& f, F&& func)
{
  return f.then([func] (boost::future<T> f) {
    return func(f.get());
  });
}
 
int main()
{
  boost::future<int> f1 = boost::async([]() -> int
  {
    int i;
    if (std::cin >> i) {
      return i;
    } else {
      throw std::runtime_error("No input");
    }
  });
 
  // boost::future<std::string> f2 = f1.then([](boost::future<int> f) {
  //   return std::to_string(f.get());
  // });
  boost::future<std::string> f2 = then_by_value(f1, [](int x) {
    return std::to_string(x);
  });
 
  try {
    std::cout << f2.get() << std::endl;
  } catch (std::exception const& e) {
    std::cerr << e.what() << std::endl;
  }
}

C++14への提案のN3784 (PDF)やBoost.Threadに存在するfuture::thenは、「futureを実引数に取る関数」を実引数として受け取ります。それに加えて、「中の値を実引数に取る関数」を実引数として受け取るものも欲しいという話でした。


スポンサード リンク

この記事のカテゴリ

  • ⇒ future::thenの値バージョン