GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::packaged_task - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. future
  3. packaged_task

最終更新日時: 2026年09月19日 21時31分51秒 (JST)
rotarymars が更新

履歴 編集

class template
<future>

std::packaged_task(C++11)

namespace std {
  template <class> class packaged_task; // 宣言のみで定義なし

  template <class R, class... ArgTypes>
  class packaged_task<R(ArgTypes...)>;
}

概要

packaged_taskは、「別スレッドでの処理完了を待ち、その処理結果を取得する」といった非同期処理を実現するためのクラスであり、futureクラスと組み合わせて使用する。packaged_taskに登録した非同期実行する関数の戻り値をfutureが読み取る。

packaged_taskとfutureは内部的に同一の共有状態を参照する。

テンプレートパラメータ:

  • R(ArgTypes...) : 非同期実行する関数のシグニチャ。Rが戻り値の型、ArgTypes...が引数の型

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ C++11
(destructor) デストラクタ C++11
operator= 代入演算子 C++11
swap 他のpackaged_taskオブジェクトと値を入れ替える C++11
valid 共有状態を持っているかを確認する C++11
reset 共有状態を作り直す C++11

結果の取得

名前 説明 対応バージョン
get_future 結果取得のためのfutureオブジェクトを取得する C++11

実行

名前 説明 対応バージョン
operator() タスクを実行し、戻り値を共有状態に格納する C++11
make_ready_at_thread_exit タスクを実行し、スレッド終了時に準備完了状態にする C++11

非メンバ関数

名前 説明 対応バージョン
swap 2つのpackaged_taskオブジェクトを入れ替える C++11

推論補助

名前 説明 対応バージョン
(deduction_guide) クラステンプレートの推論補助 C++20

その他

名前 説明 対応バージョン
uses_allocator packaged_taskによる特殊化 C++11
C++20で削除

例

#include <iostream>
#include <thread>
#include <future>
#include <utility>

int calc()
{
  int sum = 0;
  for (int i = 0; i < 10; ++i) {
    sum += i + 1;
  }
  return sum;
}

int main()
{
  std::packaged_task<int()> task(calc); // 非同期実行する関数を登録する
  std::future<int> f = task.get_future();

  // 別スレッドで計算を行う
  std::thread t(std::move(task));
  t.detach();

  try {
    // 非同期処理の結果値を取得する
    std::cout << f.get() << std::endl;
  }
  catch (...) {
    // 非同期実行している関数内で投げられた例外を捕捉
  }
}

出力

55

バージョン

言語

  • C++11

処理系

  • Clang: 9.0.1 ✅
  • GCC: 4.7.0 ✅
  • Visual C++: 2012 ✅

参照

  • LWG Issue 2000. Missing definition of packaged_task specialization of uses_allocator
    • C++11で、uses_allocatorの特殊化がtrue_typeから派生することが規定された。宣言のみで内容が規定されていなかった
  • LWG Issue 2030. packaged_task::result_type should be removed
    • C++11で、メンバ型result_typeが削除された。関数オブジェクトとしての慣習に従ったものだったが、このクラスは直接呼び出して値を返すものではないため
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.