liveBook · Manning

Std::function

As explained in Learn C++ by Example

std::function is a C++ standard library polymorphic function wrapper that can store and invoke callable objects with a specified signature.

std::function is a general-purpose C++ wrapper for a callable object, including a lambda or named function. Its template signature states the return type followed by the parameter types, such as std::function<std::string(int, int)>. section 3.1.3

Adding clues to a number-guessing game

A guessing function accepts std::function<std::string(int, int)> message and calls message(number, guess) after an incorrect guess. The caller can supply a lambda that formats “too small” or “too big” feedback, separating game flow from message policy. section 3.1.3

Because different lambdas have different types, std::function can give them a common type for storage in a vector. A clue list can then test length, primality, and matching digits in order. This flexibility may produce larger, slower code because the callable can no longer be inlined. section 3.3.5 section 3.4

Listing 3.20 Pulling it all together
int main()
{
    check_properties();
    auto check_prime = [](int guess) {
        return std::string((is_prime(guess)) ? "" : "Not prime\n");
    };
 
    auto check_length = [](int guess) {
        return std::string((guess < 100000) ? "" : "Too long\n");
    };
 
    const int number = some_prime_number();
    auto check_digits = [number](int guess) {
        return std::format("{}\n",
             check_which_digits_correct(number, guess));    
    };
    std::vector<
        std::function<std::string(int)>
    > messages                                         #1
    {
        check_length,
        check_prime,
        check_digits 
    };
    guess_number_with_more_clues(number, messages);    #2
}

Inspect the complete clue pipeline: lambdas are stored as std::function<std::string(int)> values in a vector and passed to the guessing game. section 3.3.5

How Learn C++ by Example covers it

How deep it goes
Defines signatures, initialization, invocation, containers, and performance trade-offs, while deferring constrained templates and parameter packs.
Examples
Demonstrates too-high or too-low messages, prime checks, length checks, and digit-matching clues.
What it assumes
Builds on lambdas and callable syntax while using a guessing game to clarify why a callable needs an expressible type.
What you can do after
Apply it via the C++ standard library to pass and store differently typed callables behind one signature.
How it connects
Connects lambdas, callable objects, templates, concepts, and vectors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.