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




