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 ;
(depuis C++11)

Invoque la fonction cible stockée avec les paramètres args .

Effectue effectivement INVOKE<R> ( f, std:: forward < Args > ( args ) ... ) , où f est l' objet cible de * this .

Table des matières

Paramètres

args - paramètres à passer à la fonction cible appelable stockée

Valeur de retour

Aucun si R est void . Sinon, la valeur de retour de l'invocation de l'objet appelable stocké.

Exceptions

Lance std::bad_function_call si * this ne stocke pas une cible de fonction appelable, c'est-à-dire ! * this == true .

Exemple

L'exemple suivant montre comment std::function peut être passé à d'autres fonctions par valeur. Il montre également comment std::function peut stocker des lambdas.

#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);
}

Sortie possible :

bad_function_call
1
2
42
Hi 42

Voir aussi

invoque la cible
(fonction membre publique de std::move_only_function )
appelle la fonction stockée
(fonction membre publique de std::reference_wrapper<T> )
l'exception lancée lors de l'invocation d'un std::function vide
(classe)
(C++17) (C++23)
invoque n'importe quel objet Callable avec les arguments donnés et possibilité de spécifier le type de retour (depuis C++23)
(modèle de fonction)