Reputation: 1011
Getting a weird error which I could not solve.
I have few files, Store.cpp, Store.h (Class Store is defined here), Order.cpp, Order.h (class Order is defined here).
Store.cpp has #include "Order.h"
.
Inside the class Order
I have a few setters and getters in the public section, one of them is :
void setStatus(const OrderStatus& orderStatus);
OrderStatus is an enum.
When I'm trying to use it in Store.cpp with the following line :
(*itr).setStatus(ORDER_DONE);
I get this error from eclipse :
Invalid arguments ' Candidates are: void setStatus(const enum {order.h:140} &) '
And this error from GCC :
Store.cpp:250:31: error: no matching function for call to âOrder::setStatus(OrderStatus) constâ Store.cpp:250:31: note: candidate is:
order.h:47:7: note: void Order::setStatus(const OrderStatus&)
order.h:47:7: note: no known conversion for implicit âthisâ parameter from âconst Order*â to âOrder*â
I really do not know where the const came from (line 250).
Upvotes: 0
Views: 10036
Reputation: 67802
std::set
is used for storing immutable value types. They have to be immutable, because otherwise you can break the ordering constraints when you mutate them.
If you want to associate a mutable value with a key (which is immutable for the same reason), use std::map
instead.
The mechanics of it are that:
std::set<Order>::iterator iter = ...;
iter->setStatus(ORDER_DONE);
doesn't work because *iter
yields Order const &
and your method isn't const.
I mentioned in a comment two ways to avoid the problem, but they both do so by subverting const correctness, and I strongly recommend not using either of them. But, for completeness:
const_cast<Order&>(*iter).setStatus(ORDER_DONE);
will make it compile, as would changing the Order class itself:
class Order {
mutable OrderStatus status;
public:
void setStatus(OrderStatus s) const { status = s; }
};
Either of these could also break std::set
's ordering invariant if the status is used in the comparison. The first version is saying "just trust me" and sidesteps const correctness completely, while the second explicitly communicates that the status is not a "real" part of the object's state and won't be used for sorting.
Seriously, use the right data structure instead.
Upvotes: 3
Reputation: 275820
In order to change elements of a set
, you must remove the element to a local copy, modify it there, then insert it back in,
set
s are fragile and assume elements do not change their order while within the container, which is why access to the elements is const
.
Upvotes: 2