When you are creating a lambda expression, its implementation creates a new class.Each lambda creates a separate class and has a different type. Even when many lambda expressions receive the same arguments and return the same type, each of them will be a different class; that is, a different type. C++ from version 11 on, incorporates a wrapper for any of the following functions with std::function and makes it easy to pass around lambda expressions: The following code snippets provides example that uses "std::function" to create the a function, which receives the function to be executed within a for_each as an argument.
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
void run_within_for_each(std::function<void (int)> func)
{
vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
for_each(numbers.begin(), numbers.end(), func);
}
int main()
{
auto func1 = [](int y)
{
cout << y << endl;
};
auto func2 = [](int z)
{
cout << z * 2 << endl;
};
run_within_for_each(func1);
run_within_for_each(func2);
}
The "run_within_for_each" function receives a std::function, so it is possible to call this function with a lambda expression that returns void and receives an int as an argument. The function declares the vector and executes a for_each with the received std::function as the function to be executed for each int value. The main method declares two different lambda expressions that receive an int argument and make one call to the run_within_for_each with each of these lambda expressions. In case you want to pass around a lambda expression that receives two int arguments and returns a bool value, you can use std::function. It is also possible to use std::function to specify the return type for any function. For example, the following function returns a std::function. The code returns a lambda expression that receives an int as a parameter and returns a bool value, wrapped in std::function:
std::function<bool(int)> create_function()
{
return [](int x)
{
return (x < 100);
};
}
The combination of lambda expressions with the std::function can boost your productivity and reduce a huge amount of code.
for more information please see here a wonderful article from "Gastón Hillar"
Aucun commentaire:
Enregistrer un commentaire