Passing and storing lambda function as callbacks in C++

Lambda functions are one of the most exciting features which are present in C++ programming (C++11). Lambda functions(also referred to as closures) are just like normal functions which mean:

  • Coders can pass arguments to it.
  • It returns results.

Lambda functions can be written inline in our code to pass into another function. These functions are anonymous because they don’t need to be named or reused.
Lambda functions can be declared as auto and can be used anywhere in the program.
With the use of lambda functions, creating quick functions has become much easier because now the coders can use lambda instead of writing a separate named function.

Using Lambda function in C++

The basic syntax for using lambda functions in C++ programming is:

[ captures ] (parameters) -> returnTypesDeclaration { Statements; }
  • [captures]: This is used to specify which outside variables are available to be used by the lambda functions and whether these variables should be called by value or by reference.
  • (parameter): This is used to give the arguments that are going to be passed into the function. This is optional because sometimes the functions take zero arguments.
  • -> returnTypeDeclaration: This is used to specify the return type after the function is evaluated. It is a good practice to specify the return type.
  • { Statements; }: These are the statements provided and are accessed by the lambda variables.

An example of a lambda function is as follows:

#include <iostream>
using namespace std;
int main()
      auto display = []() { cout << "Statements" << endl; }; //The function named "display" is created.
      display(); //The function is called.


Passing and Storing Lambda Functions

Lambda functions are also registered as a callback. We are able to use lambda functions as callbacks with the help of std:: function. To pass the value we generally use the following methods:

  • Pass by value.
  • Pass by reference.

Let us demonstrate this with example code and use C++ as the programming for the example code.

typedef std::function<int(int)> CallbackFunction;

class ClassName
    void connectCallback(CallbackFunction cb) //Function is created and parameters are taken.
        m_cf = cf;

    void test() //CallBack testing
        printf("ClassName::test() calling callback.\n"); //Statements of the functions.
        int i = m_cf(10);

        printf("Result (45): %d\n", i);

    CallbackFunction m_cf;

Hence, this explains the passing and storing of lambda functions as callbacks in C++.

To learn more, check out more content at CodeSpeed

Also, check out Find recurring sequence of a fraction in C++

Leave a Reply

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