A6SE
A6SE

Reputation: 270

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.

Upvotes: 1

Views: 851

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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.

Upvotes: 2

Fabio A. Correa
Fabio A. Correa

Reputation: 2036

Array Array::operator+=(const int a) {
    std::function<int(int)> my_f([&a](int b) { return b + a; });
    return transform(my_f);
}

Upvotes: 1

Related Questions