• Home
  • 6.18 std::function

6.18 std::function

View Categories

6.18 std::function

1 min read

Table of Contents

std::function is a general-purpose polymorphic function wrapper provided by the C++ Standard Library. It can store, copy, and invoke callable objects such as ordinary functions, lambda expressions, and function objects.

The type of a std::function object is specified using a function signature consisting of the return type and parameter types. This allows different kinds of callable objects with compatible signatures to be used through the same interface.

Source Code #

#include <iostream>
#include <functional>

int add(int first, int second)
{
    return first + second;
}

int main()
{
    std::function<int(int, int)> operation = add;

    int result = operation(10, 20);

    std::cout << "Result: " << result << '\n';

    return 0;
}

Output #

Result: 30

Explanation #

  • #include <functional> provides std::function.
  • std::function<int(int, int)> declares a function wrapper that can store a callable returning int and accepting two int parameters.
  • operation = add stores the add() function inside the std::function object.
  • operation(10, 20) invokes the stored callable with 10 and 20 as arguments.
  • std::function can store different callable types as long as their signatures are compatible.
  • Unlike a function pointer, std::function can also store lambda expressions, function objects, and other callable objects.
  • std::function provides a uniform interface for invoking different kinds of callable objects.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *