Show lambda with parameters are used? How to pass parameters to them?

It works exactly like with any other type of callable object:

#include <iostream>

int main()
{
    auto l = [] (int i) { std::cout << "The answer is " << i; };
    l(42);
}

Also notice, that you do not need to store a lambda in a variable in order to invoke it. The following is an alternative way to rewrite the above program:

#include <iostream>

int main()
{
    [] (int i) { std::cout << "The answer is " << i; } (42);
    //                                                 ^^^^
    //                                 Invoked immediately!
}

The type of a lambda function (the so-called "lambda closure") is defined by the compiler, and is a functor with a call operator whose signature is the one you specify when defining the lambda. Therefore, you call a lambda exactly as you would call a functor (i.e. exactly as you would call a function - or any callable object).

Thus, if you want to assign a lambda to an object, the best practice is to let the compiler deduce its type by using auto. If you do not want or cannot use auto, then you may:

  1. Use function pointers for non-capturing lambdas (capturing lambdas are not convertible to function pointers). In the above case, thus, the following will also work:

    #include <iostream>
    
    int main()
    {
        void (*f)(int) = [] (int i) { std::cout << "The answer is " << i; };
        f(42);
    }
    
  2. Use std::function (this is always possible, even if the lambda is capturing):

    #include <iostream>
    #include <functional>
    
    int main()
    {
        std::function<void(int)> f = [] (int i) 
                                   { std::cout << "The answer is " << i; };
        f(42);
    }
    
Answer from Andy Prowl on Stack Overflow
Top answer
1 of 3
35

Show lambda with parameters are used? How to pass parameters to them?

It works exactly like with any other type of callable object:

#include <iostream>

int main()
{
    auto l = [] (int i) { std::cout << "The answer is " << i; };
    l(42);
}

Also notice, that you do not need to store a lambda in a variable in order to invoke it. The following is an alternative way to rewrite the above program:

#include <iostream>

int main()
{
    [] (int i) { std::cout << "The answer is " << i; } (42);
    //                                                 ^^^^
    //                                 Invoked immediately!
}

The type of a lambda function (the so-called "lambda closure") is defined by the compiler, and is a functor with a call operator whose signature is the one you specify when defining the lambda. Therefore, you call a lambda exactly as you would call a functor (i.e. exactly as you would call a function - or any callable object).

Thus, if you want to assign a lambda to an object, the best practice is to let the compiler deduce its type by using auto. If you do not want or cannot use auto, then you may:

  1. Use function pointers for non-capturing lambdas (capturing lambdas are not convertible to function pointers). In the above case, thus, the following will also work:

    #include <iostream>
    
    int main()
    {
        void (*f)(int) = [] (int i) { std::cout << "The answer is " << i; };
        f(42);
    }
    
  2. Use std::function (this is always possible, even if the lambda is capturing):

    #include <iostream>
    #include <functional>
    
    int main()
    {
        std::function<void(int)> f = [] (int i) 
                                   { std::cout << "The answer is " << i; };
        f(42);
    }
    
2 of 3
5
auto lambda = [] (int a, int b) { return a + b; };
assert(lambda(1, 2) == 3);
🌐
Cppreference
en.cppreference.com › w › cpp › language › lambda.html
Lambda expressions (since C++11) - cppreference.com
Executes the body of the lambda expression, when invoked. When accessing a variable, accesses its captured copy (for the entities captured by copy), or the original object (for the entities captured by reference). The parameter list of operator() is params if it is provided, otherwise the parameter ...
Discussions

Use a lambda as a parameter for a C++ function - Stack Overflow
I would like to use a lambda as a parameter for a C++ function, but I don't know which type to specify in the function declaration. What I would like to do is this: void myFunction(WhatToPutHere l... More on stackoverflow.com
🌐 stackoverflow.com
When to use a lambda over a function pointer?
So there are three main things I use lambdas for (NOTE: The Reddit numbered list functionality is literally so shitty that I cannot put any code blocks between numbered entries whatsoever, so you get no numbers): They make it easier to pass a function as an argument. Consider the situation where you have a very simple thing to do, but creating an entire separate function is both harder to maintain as well as more difficult to mentally parse. For example: int example(std::vector nums) { return std::accumulate(nums.begin(), nums.end(), 0, [](int acc, int num){ return num > 0 ? acc + num : acc; }); } They allow you to easily bind arguments for functions without needing to use the unnecessarily complicated std::bind. Before lambdas, C++ tried to get first class function using std::function and std::bind. The std::function thing mostly remains, but std::bind has been wholesale replaced by lambdas. struct MyObject { int doSomething(int argument); }; int deriveInfo(std::function f); int example() { MyObject o; // Instead of doing this: // return deriveInfo(std::bind(&MyObject::doSomething, &o)); // You do this: return deriveInfo([&o](int arg){ return o.doSomething(arg); }); } They allow you to create function objects without needing to do all of the class or struct definitions manually. A lambda is effectively an object that runs the function provided upon a call to operator(). As such, if you need to have multiple different function objects passed to the same object or template, this makes it very easy to do so. constexpr static auto A = [](int a, int b){ return example(a * b); }; constexpr static auto B = [](int a, int b){ return example(a + b); }; constexpr static auto C = [](int a, int b){ return example(a - b); }; template constexpr static inline void doSomething(Func f) { f(10, 5); } void someFunc() { doSomething(A); doSomething(B); doSomething(C); } I find lambdas to be quite useful and would be very disappointed if I was forced to make it work with just function pointers. More on reddit.com
🌐 r/cpp_questions
27
19
September 10, 2023
c++ - Proper way to receive a lambda as parameter by reference - Stack Overflow
Are there other ways to define a lambda parameter? ... You cannot have an auto parameter. You basically have two options: Option #1: Use std::function as you have shown. More on stackoverflow.com
🌐 stackoverflow.com
How do I pass a lambda to a method as a parameter?
Try Func. The last generic type parameter in Func is the return type, so you need three of them: two for the parameters and one for the return type. More on reddit.com
🌐 r/csharp
27
31
March 6, 2021
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › language-reference › operators › lambda-expressions
Lambda expressions - Lambda expressions and anonymous functions - C# reference | Microsoft Learn
January 24, 2026 - Before C# 14, you must include the explicit type on a parameter if it has any modifiers, such as ref or out. In C# 14, that restriction is removed. However, you must still declare the type if you use the params modifier. Use discards to specify two or more input parameters of a lambda expression that aren't used in the expression:
🌐
Medium
kcwong-joe.medium.com › passing-a-function-as-a-parameter-in-c-a132e69669f6
Passing a function as a parameter in C++ | Medium - Joe Wong
March 8, 2021 - std::bind(&I_have_a_usefull_function::func, true, std::placeholders::_1)The first parameter "&I_have_a_usefull_function::func" is the function pointer you want to pass.Other parameters are the argument pass to the funciton pointer. In this example, "this" is passed to inside the function body. In this example, the first argument is fixed as true. The second argument and third are set as placeholders 1 and 2 which can be input later. Pro: 1. Valid to pass the local variable in the lambda function.
🌐
Quora
quora.com › Can-lambda-functions-be-used-as-parameters-of-other-functions-in-C-If-so-how-can-this-be-done
Can lambda functions be used as parameters of other functions in C++? If so, how can this be done? - Quora
Answer: Lambdas are essentially each their own type. To pass them to function you must so rely on type deduction and eventually apply type cancellation. To have type deduction, the function taking the lambda must be a template, or having an “auto” type parameter (essentially a shortcut for temp...
Find elsewhere
🌐
Medium
ggulgulia.medium.com › c-20-lambda-expression-and-template-syntax-7f6ae2f9e7cd
C++20 lambda expression and template syntax | by Gajendra Gulgulia | Medium
July 26, 2021 - The above code snippet can be explained as follows: Comment (1) indicates that struct IsVector , which is a template class, inherits publicly std::false_type by default. Comment (2) indicates that the struct IsVector inherits publicly from std::true_type if the template parameter T to the struct is of type std::vector<T> . Comment (3) indicates that within the lambda expression a static_assert to check during compile time, that the parameter passed to the lambda expression is indeed a vector by making use of the IsVector object.
🌐
Johannesugb
johannesugb.github.io › cpu-programming › how-to-pass-lambda-functions-in-C++
How To Pass Lambda Functions in C++ (By Value, By L-Value Reference, By Universal Reference) - Johannes Unterguggenberger
January 9, 2021 - This indicates that especially the latter variant – the one accepting a universal reference – is the most versatile one since it is the only variant which accepts all different kinds of parameters: mutable lambdas, move-only lambdas, and – of course – ordinary lambdas. As reasoned in the answers and comments of the StackOverflow question mentioned initially, the by value variant is probably the one that you should default to.
🌐
Built In
builtin.com › software-engineering-perspectives › c-plus-plus-lambda
C++ Lambda Expressions Explained | Built In
A lambda in C++ is an expression used to simplify code when defining anonymous function objects (functors). Lambdas allow for functors to be defined directly where they are invoked or be passed as function arguments.
🌐
Reddit
reddit.com › r/cpp_questions › when to use a lambda over a function pointer?
r/cpp_questions on Reddit: When to use a lambda over a function pointer?
September 10, 2023 -

Question seems simple enough.
I've never really understood then point of lambdas. To me the code seems messy, why not use a function pointer instead?

Top answer
1 of 10
25
So there are three main things I use lambdas for (NOTE: The Reddit numbered list functionality is literally so shitty that I cannot put any code blocks between numbered entries whatsoever, so you get no numbers): They make it easier to pass a function as an argument. Consider the situation where you have a very simple thing to do, but creating an entire separate function is both harder to maintain as well as more difficult to mentally parse. For example: int example(std::vector nums) { return std::accumulate(nums.begin(), nums.end(), 0, [](int acc, int num){ return num > 0 ? acc + num : acc; }); } They allow you to easily bind arguments for functions without needing to use the unnecessarily complicated std::bind. Before lambdas, C++ tried to get first class function using std::function and std::bind. The std::function thing mostly remains, but std::bind has been wholesale replaced by lambdas. struct MyObject { int doSomething(int argument); }; int deriveInfo(std::function f); int example() { MyObject o; // Instead of doing this: // return deriveInfo(std::bind(&MyObject::doSomething, &o)); // You do this: return deriveInfo([&o](int arg){ return o.doSomething(arg); }); } They allow you to create function objects without needing to do all of the class or struct definitions manually. A lambda is effectively an object that runs the function provided upon a call to operator(). As such, if you need to have multiple different function objects passed to the same object or template, this makes it very easy to do so. constexpr static auto A = [](int a, int b){ return example(a * b); }; constexpr static auto B = [](int a, int b){ return example(a + b); }; constexpr static auto C = [](int a, int b){ return example(a - b); }; template constexpr static inline void doSomething(Func f) { f(10, 5); } void someFunc() { doSomething(A); doSomething(B); doSomething(C); } I find lambdas to be quite useful and would be very disappointed if I was forced to make it work with just function pointers.
2 of 10
13
Keep in mind a lambda is syntactical sugar for a functor, not a function pointer. Function pointers are very bad from a performance perspective since it prevents inlining. Lambdas and functors are equivalent though.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › lambda-expression-in-c
Lambda Expression in C++ - GeeksforGeeks
#include <iostream> using namespace ... of x with itself. Syntax of lambda Function · Parameters: These parameters are similar to the function parameters in every way....
Published   1 month ago
🌐
Quora
quora.com › C++-How-to-pass-a-lambda-function-as-a-parameter-of-another-function
C++: How to pass a lambda function as a parameter of another function? - Quora
To pass them to function you must so rely on type deduction and eventually apply type cancellation. To have type deduction, the function taking the lambda must be a template, or having an “auto” type parameter (essentially a shortcut for template). This will instatiate the function as many time as the different lambdas you can pass to it.
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › cpp › lambda-expressions-in-cpp
Lambda expressions in C++ | Microsoft Learn
A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; }; In C++14, if the parameter type is generic, ...
🌐
Cprogramming.com
cprogramming.com › c++11 › c++11-lambda-closures.html
C++11 - Lambda Closures, the Definitive Guide - Cprogramming.com
How to begin Get the book · C tutorial C++ tutorial Game programming Graphics programming Algorithms More tutorials
🌐
Learn C++
learncpp.com › cpp-tutorial › introduction-to-lambdas-anonymous-functions
20.6 — Introduction to lambdas (anonymous functions) – Learn C++
January 3, 2020 - If C++20 capable, use auto as the parameter’s type. Otherwise, use a function with a type template parameter or std::function parameter (or a function pointer if the lambda has no captures).
🌐
Standard C++
isocpp.org › wiki › faq › cpp14-language
C++14 Language Extensions, C++ FAQ
Lambda function parameters can now be auto to let the compiler deduce the type.
🌐
University of Chicago
naipc.uchicago.edu › 2014 › ref › cppreference › en › cpp › language › lambda.html
Lambda functions (since C++11) - cppreference.com
if the body consists of the single return statement, the return type is the type of the returned expression (after rvalue-to-lvalue, array-to-pointer, or function-to-pointer implicit conversion) otherwise, the return type is void · 4) Omitted parameter list: function takes no arguments, as if the parameter list was () The lambda expression constructs an unnamed temporary object of unique unnamed non-union non-aggregate type, known as closure type, which has the following members: Executes the body of the lambda-expression, when invoked.
🌐
DZone
dzone.com › articles › all-about-lambda-functions-in-cfrom-c11-to-c17
All About Lambda Functions in C++ (From C++11 to C++17)
May 8, 2020 - Lambda with a variable parameter pack will be useful in many scenarios like debugging, repeated operation with different data input, etc. Typically, a lambda's function call operator is const-by-value, which means lambda requires the mutable ...