Lambda function passed as parameter

I have the following function:

template <typename Range> Range FindFirstIf(Range rng, bool (*Function)(typename Range::ConstReference value)) 

To this function, I am trying to pass a lambda function as follows:

 rng = FindFirstIf(rng, [](const float& val) { return (v < 0.0f); }); 

Where rng is the range of the float list, so Range::ConstReference is defined as const float&

My compiler (gcc) complains about type mismatch

 C:\Programming\Collections\main.cpp|24|note: mismatched types 'bool (*)(typename Range::ConstReference)' and 'main(int, char**)::< lambda(const float&) >'| 

Can someone tell me what is wrong with my code?

Edit:

When I pass a function like this, it works:

bool (*func)(const float& v) = [](const float& v) { return v < 0.0f; };

When I try to use the auto keyword, this is the same problem as before:

 auto func = [](const float& v) { return v < 0.0f; }; 
+2
source share
1 answer

I suspect that either you have type-o in your code, or you are using a version of gcc that does not fully implement lambdas (or, possibly, both).

If your example:

 [](const float& val) { return (val < 0.0f); } 

(v → val)

and if Range::ConstReference is const float& , then the code is legal C ++ 11.

The hard part here is that some lambdas will implicitly convert to a function pointer. That is, these lambdas without lambda capture are converted to a function pointer with an identical signature.

It:

 template <class Range> Range FindFirstIf(Range, bool (*Function)(typename Range::ConstReference value)); struct range { using ConstReference = const float&; }; int main() { range rng; rng = FindFirstIf(rng, [](const float& val) { return (val < 0.0f); }); } 

compiles for me.

With a few quotes with gcc online compilers, this seems like a bug in gcc 4.8, fixed in 4.9.

+2
source

Source: https://habr.com/ru/post/1258388/


All Articles