Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Passing polymorphic lambda to a function

Tags:

c++

lambda

c++14

I would like to pass a polymorphic lambda function which will perform certain operation (i.e. == or <= or < etc.) on different data types. So I would like to do operation like this:

bool func(bool (* f)(auto a, auto b))
{
    int a = 1, b = 2;
    float c = 3, d = 4;
    return f(a, b) || f(c, d);
}

to later execute it like this:

func([](auto a, auto b) -> bool { return a == b; });
func([](auto a, auto b) -> bool { return a <= b; });
func([](auto a, auto b) -> bool { return a < b; });

But unfortunately declaring a function pointer this way (with parameter of type auto) is not allowed. How should I do this properly?

like image 448
no one special Avatar asked Jan 03 '23 03:01

no one special


1 Answers

This works just fine:

template<class F>
bool func(F f)
{
    int a = 1, b = 2;
    float c = 3, d = 4;
    return f(a, b) || f(c, d);
}

int main()
{
    func([](auto a, auto b) -> bool { return a == b; });
    func([](auto a, auto b) -> bool { return a <= b; });
    func([](auto a, auto b) -> bool { return a < b; });
}
like image 195
o11c Avatar answered Jan 05 '23 19:01

o11c