Reputation: 13
I am trying to sort a vector of a custom class using a lambda function, but somewhere I am getting a discarded const
that I don't understand.
I have tried looking for answers here already, and while many people have asked almost the exact same question, none of them seem to be the same problem. I don't disallow the move constructor, nor do I call a non-const member/member function in the sort (At least that I am aware of. Clearly I am doing something wrong.) The closest I can think of is I do return the value of a non-const member, but I do that through a const function, and I explicitly want to do that. I want public facing member functions that can't change anything, with private facing members that can be changed internally (but not by any public facing function). The only really odd things I am doing (which I don't believe has any impact on this) are that my class is non-copyable, and has a non-copyable member (move is fine).
class MyClass{
public:
const SortByThis() { return internal_value; } //Edit: This declaration is the problem, as noted in the accepted answer.
MyClass(SortByThis, BigNonCopyableDataStrcuture);
MyClass(MyClass&)=delete; //No copy allowed. Only move.
private:
int internal_value;
BigNonCopyableDataStructure_t big_structure;
}
std::vector<MyClass> vec;
DoFillVec(vec); //Vec now has many items but is not sorted
std::sort(vec.begin(), vec.end(), [](const MyClass &lhs, const MyClass &rhs){return lhs.SortByThis() < rhs.SortByThis();});
//This is where things scream at me.
//Project/Module.cc:226:95: error: passing ‘const Namespace::Module::MyClass’ as ‘this’ argument discards qualifiers [-fpermissive]
I expect this to sort the vector, but instead the compiler complains that I am doing something wrong, and I don't understand exactly what I'm doing wrong. At this point, I am reduced to twiddling things until it compiles (and isn't that a sick feeling).
Upvotes: 0
Views: 205
Reputation: 10740
SortByThis
isn't declared correctly. The const
goes after the function, not before:
int SortByThis() const { return internal_value; }
Let us know if this fixes the problem!
Upvotes: 1