cpp-funciones-lambda

What are Lambda Functions in C++

  • 5 min

In C++, a lambda function is a compact syntax for defining anonymous functions, without the need to declare it explicitly as a traditional function.

These functions are especially useful for simple and quick operations. For example, when dealing with operations on collections, such as filtering, mapping, or reducing.

If you want to learn more, check out the Introduction to Programming Course

Lambda Function Syntax

The basic syntax of a lambda function in C++ is as follows:

[capture](parameters) -> return_type { body }
Copied!
  • Capture: List of variables from the environment that the lambda can use.
  • Parameters: List of input parameters, separated by commas if there is more than one.
  • Return type: Type of value returned by the lambda, optional if the type is deducible.
  • Body: The code that executes when the lambda is invoked.

Basic Example

Here is a basic example of a lambda function that adds two numbers:

#include <iostream>

int main() {
    auto add = [](int x, int y) -> int {
        return x + y;
    };

    std::cout << "Sum: " << add(5, 3) << std::endl; // Output: 8

    return 0;
}
Copied!

In this example,

  • The lambda function add takes two parameters x and y, and returns their sum.
  • The keyword auto is used to deduce the type of the lambda, and -> int specifies the return type.

Variable Capture

Lambda functions can capture variables from the context in which they are defined. There are different capture modes:

  • By value (=): Captures a copy of the variables.
  • By reference (&): Captures variables by reference, allowing modification of their value.
  • Mixed: Combination of captures by value and by reference.
#include <iostream>

int main() {
    int value = 10;

    auto lambda = [value]() {
        std::cout << "Value: " << value << std::endl;
    };

    lambda(); // Output: Value: 10

    return 0;
}
Copied!
#include <iostream>

int main() {
    int value = 10;

    auto lambda = [&value]() {
        value++;
        std::cout << "Value: " << value << std::endl;
    };

    lambda(); // Output: Value: 11
    std::cout << "Value after lambda: " << value << std::endl; // Output: Value after lambda: 11

    return 0;
}
Copied!

Use in Higher-Order Functions

Lambda functions can be passed as arguments to other functions that accept functions or function objects.

Example with std::function:

#include <iostream>
#include <functional>

void Execute(std::function<void()> func) {
    func();
}

int main() {
    auto message = []() {
        std::cout << "Hello from a lambda function" << std::endl;
    };

    Execute(message);

    return 0;
}
Copied!

Lambdas Capturing this

Lambdas can also capture this to access class members from within the lambda.

#include <iostream>

class MyClass {
private:
    int value;
public:
    MyClass(int v) : value(v) {}
    void printValue() {
        auto lambda = [this]() {
            std::cout << "Value: " << value << std::endl;
        };
        lambda();
    }
};

int main() {
    MyClass obj(42);
    obj.printValue(); // Prints 42
    return 0;
}
Copied!

In this example, the lambda captures this to access the member value of the class MyClass.

Generic Lambdas

Since C++14, lambdas can be generic, allowing them to work with different data types.

#include <iostream>

int main() {
    auto print = [](auto data) {
        std::cout << data << std::endl;
    };
    print(5);        // Prints an integer
    print(3.14);     // Prints a float
    print("Hello");   // Prints a string
    return 0;
}
Copied!

In this example, the lambda print is able to handle different data types thanks to its generic nature.

Practical Examples