Lambdas

Returning Lambdas from Functions

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

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved