liveBook · Manning

Callable

As explained in Learn C++ by Example

A callable is a function or function-like object that can be invoked with a specified argument list.

A callable is anything that can be invoked with an argument list, including a named function, lambda, or function-like object. In a number-guessing game, a callable supplies feedback without hard-coding the feedback logic into the game. section 3.1.3

C++ offers several ways to accept callable behavior:

  • Use std::function<std::string(int, int)> when a general-purpose wrapper should accept different callable kinds. section 3.1.3
  • Use a template to preserve the callable's specific type, or constrain it with std::invocable. section 3.1.3
  • Initialize the callable with a lambda before invoking it; an empty std::function throws when called. section 3.1.3

Clues in a number-guessing game

guess_number_with_clues receives a callable that compares the hidden number and the player's guess, then prints whether the guess was too small or too big.

Listing 3.6 Providing clues if the guess is wrong
void guess_number_with_clues(unsigned number, 
        std::function<std::string(int, int)> message)
{
    std::cout << "Guess the number.\n>";
    std::optional<int> guess;
    while (guess = read_number(std::cin))
    {
        if (guess.value() == number)
        {
             std::cout << "Well done.";
             return;
        }
        std::cout << message(number, guess.value());       #1
        std::cout << '>';                                  #2
    }
    std::cout << std::format("The number was {}\n", number);
}

Browse the complete function showing callable declaration, invocation, repeated guesses, and feedback output. section 3.1.3

How Learn C++ by Example covers it

How deep it goes
Explains callable types through std::function, lambdas, templates, and std::invocable, while deferring concepts to the next chapter.
Examples
Demonstrates callable feedback in a number-guessing game that reports whether guesses are too small or too big.
What you can do after
Apply it via std::function or constrained parameters to pass customizable feedback behavior into a C++ function.
How it connects
Connects callables with std::function, lambda expressions, templates, concepts, std::invocable, and function signatures.

Also explained in

Compare how 5 books explain callable →

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.