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
