std::function::operator()(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

✨ NAME ✨

std::function::operator() - std::function::operator() (yes bestie, the name is literally the name twice and it's giving main character energy πŸ‘‘). This is the std::function::operator()(3) page from the C++ Standard Libary manual, folded in right here near the top like a little intro 🫢.


πŸ¦‹ Synopsis πŸ¦‹

R operator()( Args... args ) const;  (since C++11)

Okay so what this actually does: it invokes the stored callable function target with the parameters args. Effectively it does INVOKE<R>(f, std::forward<Args>(args)...), where f is the target object of *this. Periodt ✨.


🌸 Parameters 🌸

  • args β€” parameters to pass to the stored callable function target. That's the whole vibe πŸŽ€.

πŸ’– Return value πŸ’–

None if R is void. Otherwise, you get the return value of the invocation of the stored callable object. No cap.


πŸ’€ Exceptions πŸ’€

Throws std::bad_function_call if *this does not store a callable function target, i.e. !*this == true. So if it's empty, it's throwing hands β€” protect your vibe check, bestie 😭.

πŸ“ Example πŸ“

The following example shows how std::function can be passed to other functions by value. Also, it shows how std::function can store lambdas. Here's the exact code, including the // Run this code bit from the original:

// Run this code

#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 = [&n](){ return n; };
    call(f);

    n = 2;
    call(f);

    f = normal_function;
    call(f);
}

πŸ“ Output πŸ“

1
2
42

πŸ‘€ See also πŸ‘€

Here's every reference from the original See also zone β€” yes, all of it, because we don't skip details in this group chat πŸ’…:

  • operator() β€” invokes the target
    • (C++23) β€” public member function of std::move_only_function
  • operator() β€” calls the stored function
    • public member function of std::reference_wrapper<T>
  • bad_function_call β€” the exception thrown when invoking an empty std::function
    • (C++11) β€” class
  • invoke β€” invokes any Callable object with given arguments
  • invoke_r β€” and possibility to specify return type
    • (C++17)
    • (since C++23)
    • (C++23)
    • (function template)

okay bestie, that's the whole page β€” catch you later πŸ’– this little icon came from http://cppreference.com, dated 2024.06.10, and it's the std::function::operator()(3) page. mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from