How use/store lambdas?

Is many examples how to pass lambda to standards methods like std::sort:

#include <algorithm>
#include <cmath>

void abssort(float* x, unsigned n) {
std::sort(x, x + n,
// Lambda expression begins
[](float a, float b) {
return (std::abs(a) < std::abs(b));
} // end of lambda expression
);
}

But:
- how to store lambda to variable or structure field for further use?
- how use it in my own methods instead of std::sort?

This question is basic but I can't find such examples.
- how to store lambda to variable or structure field for further use?
Why would you do this? When used outside of its encompassing function they are just like normal free functions.

- how use it in my own methods instead of std::sort?
Either template or std::function. See:

http://www.cplusplus.com/reference/functional/function/?kw=function

With this structure you can store any kind of function including members of class/struct.
> how to store lambda to variable or structure field for further use?

Wrap it in the polymorphic function wrapper https://en.cppreference.com/w/cpp/utility/functional/function


> how use it in my own methods instead of std::sort?

Write them as templates which can accept any compatible callable object.


For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <functional>

struct my_struct
{
    int value ;
    std::function< int(int) > function ; // wrapped function object
                // this can also wrap a closure (the result of evaluating a lambda expression)

    void apply() { value = function(value) ; } // use the stored function

    // use a function passed as the argument
    template < typename FN > void apply_this( FN fn ) { value = fn(value) ; }

    friend std::ostream& operator<< ( std::ostream& stm, const my_struct& ms )
    { return stm << "my_struct { value == " << ms.value << " }" ; }
};

int main()
{
    // initialise an object with a (wrapped) lambda expression
    my_struct ms { 23, [] ( int v ) { return v*2 ; } } ;
    std::cout << ms << '\n' ; // my_struct { value == 23 }

    ms.apply() ; // use the stored function (23*2)
    std::cout << ms << '\n' ; // my_struct { value == 46 }

    ms.function = [] ( int v ) { return v*v ; } ; // change the stored function
    ms.apply() ; // use it (46*46)
    std::cout << ms << '\n' ; // my_struct { value == 2116 }

    ms.apply_this( [] ( int v ) { return v*3 ; } ) ; // pass the function to be applied (2116*3)
    std::cout << ms << '\n' ; // my_struct { value == 6348 }
}


http://coliru.stacked-crooked.com/a/056710497b6b75cd
Topic archived. No new replies allowed.