Returning Lambdas from Functions

Can I return a lambda from a function? If so, how do I specify the return type?

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.

Lambdas

An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Capturing Class Members in Lambdas
How can I capture member variables of a class when defining a lambda inside a member function?
Using Lambdas in Template Functions
How can I pass a lambda as an argument to a function template?
Using Lambdas as Comparators
Can I use a lambda as a comparator for STL containers and algorithms?
Creating Stateful Lambdas
Is it possible to create a lambda that maintains state across multiple invocations?
Creating Recursive Lambdas
Can a lambda call itself recursively?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant