Reputation: 270
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
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
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