Alexander Bily
Alexander Bily

Reputation: 965

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 like this:

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

Where rng is Range of List of floats, 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 anybody tell me what is wrong with my code?

Edit:

When I pass function like this, it works:

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

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

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

Upvotes: 2

Views: 600

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 218700

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

If your example was:

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

(v -> val)

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

The tricky part here is that some lambdas will implicitly convert to a function pointer. That is, those lambdas with no lambda-capture will convert to a function pointer with an identical signature.

This:

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 little poking around with online gcc compilers, this appears to be a bug in gcc 4.8, fixed in 4.9.

Upvotes: 2

Related Questions