A6SE A6SE - 1 year ago 126
C++ Question

C++ error with functions as parameters, initial value of reference to non-const must be an lvalue

So, here is the part of the code in relation to the error:

Array Array::transform(std::function<int(int)>&f)
std::for_each(niz, niz + n, [&f](Tacka &r) {r.setX(f(r.getX())), r.setY(f(r.getY())); });
return *this;

Array Array::operator+=(const int a)
return transform([&a](int b) { return b + a; });

The error appears when trying to send a lambda function as an argument.

If I remove a reference from "transform" function parameter, the code works. But I don't understand why it didn't work in the first place.

How can I fix the code without removing a reference from parameter?

Thank you for your time.

Answer Source

You call your method transform and pass the object of the type std::function as an expression that creates a temporary object of a lambda type.

return transform([&a](int b) { return b + a; });

You could declare the parameter like

const std::function<int(int)>&f

to avoid the message.

A temporary object may not be bound to a non constant reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download