Yes, you can return a lambda from a function. However, specifying the return type can be a bit tricky.
One way to do this is to use auto
as the return type and let the compiler deduce it:
#include <iostream>
auto MakeLambda() {
return [] {
std::cout << "Hello from Lambda!\n";
};
}
int main() {
auto MyLambda{MakeLambda()};
MyLambda();
}
Hello from Lambda!
However, if you need to explicitly specify the return type (for example, if you're implementing a function declared elsewhere), you can use std::function
from the <functional>
 header:
#include <functional>
#include <iostream>
std::function<void()> MakeLambda() {
return [] {
std::cout << "Hello from Lambda!\n";
};
}
Here, std::function<void()>
specifies that the function returns a callable that takes no arguments and returns void
.
You can adjust the template arguments to match the parameters and return type of your lambda. For example, std::function<int(std::string)>
would be a callable that accepts a std::string
and returns an int
.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions