A lambda expression has been defined and assigned/binded to a function object. Now I'd like to assign a new function to that function object. But this assignment casuses compile error in some cases.
I understand that the error comes from the auto
keyword automatically adding const
to the function object. Is there anyway to use auto
together with other key words to remove the const
binding? I don't really believe mutable
can serve the purpose as in my code.
This post explains why without a solution. This post proposes a solution using a struct, but I wonder if there is a more elegant way to do it.
#include <functional>
#include <memory>
#include <queue>
#include <random>
#include <utility>
using namespace std;
void f1();
int main() {
srand(0);
f1();
return 0;
}
void f1() {
using my_pair = pair<int,int>;
int ref = 2;
function<bool(const my_pair &,const my_pair &)> comp_1 = [&ref](const my_pair &LHS, const my_pair &RHS) {return LHS.first-ref > RHS.first-ref;};
comp_1 = [&ref](const my_pair &LHS, const my_pair &RHS) {return LHS.first < RHS.first;};
// So far so good.
auto comp_2 = [&ref](const my_pair &LHS, const my_pair &RHS) mutable {return LHS.first-ref > RHS.first-ref;};
// Compile error below!
comp_2 = [&ref](const my_pair &LHS, const my_pair &RHS) mutable {return LHS.first < RHS.first;};
// Compile error above
// Applications of the function object
priority_queue<my_pair, vector<my_pair>, decltype(comp_2)> myHeap(comp_2);
for (int i=0; i<10; i++) myHeap.emplace(rand()%10,rand()%20);
while (!myHeap.empty()) {
printf("<%d,%d>\n",myHeap.top().first,myHeap.top().second);
myHeap.pop();
}
}