Namespaces
Variants

std::function<R(Args...)>:: operator()

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
R operator ( ) ( Args... args ) const ;
(C++11以降)

格納された呼び出し可能な関数ターゲットをパラメータ args で呼び出します。

実質的に INVOKE<R> ( f, std:: forward < Args > ( args ) ... ) を実行します。ここで f ターゲットオブジェクト であり、 * this のものです。

目次

パラメータ

args - 格納された呼び出し可能な関数ターゲットに渡すパラメータ

戻り値

R void の場合はなし。それ以外の場合、格納された呼び出し可能オブジェクトの呼び出しの戻り値。

例外

std::bad_function_call をスローする(throwする)条件: * this が呼び出し可能な関数ターゲットを保持していない場合、すなわち ! * this == true の場合。

以下の例は、 std::function が値渡しで他の関数に渡せる方法を示しています。また、 std::function がラムダ式を格納できることも示しています。

#include <functional>
#include <iostream>
void call(std::function<int()> f) // can be passed by value
{ 
    std::cout << f() << '\n';
}
int normal_function()
{
    return 42;
}
int main()
{
    int n = 1;
    std::function<int()> f;
    try
    {
        call(f);
    }
    catch (const std::bad_function_call& ex)
    {
        std::cout << ex.what() << '\n';
    }
    f = [&n](){ return n; };
    call(f);
    n = 2;
    call(f);
    f = normal_function;
    call(f);
    std::function<void(std::string, int)> g;
    g = [](std::string str, int i) { std::cout << str << ' ' << i << '\n'; };
    g("Hi", 052);
}

出力例:

bad_function_call
1
2
42
Hi 42

関連項目

ターゲットを呼び出す
( std::move_only_function の公開メンバ関数)
格納された関数を呼び出す
( std::reference_wrapper<T> の公開メンバ関数)
空の std::function を呼び出したときにスローされる例外
(クラス)
(C++17) (C++23)
任意の Callable オブジェクトを指定された引数で呼び出す (戻り値の型を指定可能) (C++23以降)
(関数テンプレート)