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::function::target - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. functional
  3. function
  4. target

最終更新日時: 2026年08月24日 18時48分56秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<functional>

std::function::target(C++11)

template <class T>
T* target() noexcept;

template <class T>
const T* target() const noexcept;

概要

元となる関数を取得する。

戻り値

target_type() == typeid(T)ならば、保持している関数へのポインタを返す。そうでなければヌルポインタを返す。

備考

  • C++14までは、型Tが「ArgTypes...型をパラメータにとりRを戻り値の型とする関数、または関数オブジェクトであること」が要件とされており、それ以外の型を指定した場合の動作は未定義であった。C++17でこの要件は削除され、Tが呼び出し可能な型であるかどうかによらず、target_type() != typeid(T)であればヌルポインタを返すことが保証される。

例

#include <iostream>
#include <functional>

struct ident_functor {
  int operator()(int x) const
  { return x; }
};

int ident_func(int x)
{ return x; }

int main()
{
  // 関数オブジェクト
  {
    std::function<int(int)> f = ident_functor();
    ident_functor* p = f.target<ident_functor>();

    if (p) {
      std::cout << (*p)(1) << std::endl;
    }
  }

  // 関数ポインタ
  {
    std::function<int(int)> f = ident_func;
    using fp_type = int(*)(int);

    fp_type* p = f.target<fp_type>();

    if (p) {
      std::cout << (*p)(1) << std::endl;
    }
  }
}

出力

1
1

バージョン

言語

  • C++11

処理系

  • Clang: 3.0 ✅
  • GCC: 4.3.6 ✅
  • Visual C++: ??

参照

  • LWG Issue 2591. std::function's member template target() should not lead to undefined behaviour
    • Tが呼び出し可能型であることの事前条件が削除され、target_type() != typeid(T)のときTの呼び出し可能性によらずヌルポインタを返す、広い契約の関数となった
    • この修正は欠陥報告(DR)であり、C++11以降に遡及して適用される。元は事前条件違反として未定義動作だった領域の明文化であり、処理系は当初からヌルポインタを返していたため
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.