Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::function: copyable call wrapper

std::function stores any copyable callable matching a selected signature and invokes it through one uniform interface.

Version: C++23

Syntax

template<class Signature> class std::function;

template<class R, class... Args>
class std::function<R(Args...)> {
public:
    function() noexcept;
    template<class F> function(F&& f);
    explicit operator bool() const noexcept;
    R operator()(Args... args) const;
};

std::function<R(Args...)> from <functional> is a type-erased polymorphic wrapper. It can hold a function pointer, function object, binding, or lambda when the stored type is copyable and can be called with Args... to produce a result compatible with R. The wrapper itself is copyable and movable; copying it copies its stored target, so value captures become part of each target copy.

The example stores a lambda that captures factor by value in std::function<int(int)>. std::function::operator() invokes the stored target, so scale(5) returns 15. std::function::operator bool reports whether the wrapper has a target; the second wrapper is default-constructed, so static_cast<bool>(empty) is false and the program prints 15 0. Test the Boolean state before invoking an optional callback unless handling an empty call through an exception is intentional.

Calling an empty wrapper throws std::bad_function_call; exceptions from the target propagate. Construction may allocate and throw std::bad_alloc or any exception from initializing the stored target, including a throwing move from an rvalue argument; small-object optimization is not guaranteed. A move-only lambda does not meet the C++23 std::function contract—use std::move_only_function for that case. Reference captures do not extend object lifetimes and can leave a dangling target. target<T>() succeeds only for the exact stored type, and the wrapper signature does not preserve a noexcept qualifier.

Examples

#include <functional>
#include <iostream>

int main() {
    const int factor = 3;
    std::function<int(int)> scale = [factor](int value) {
        return factor * value;
    };
    std::function<int(int)> empty;

    std::cout << scale(5) << ' ' << static_cast<bool>(empty) << '\n';
}

Result

15 0

std::function → 15 0

Sources