Why do I get a C2440 for the
for(box& b : uset)
Error C2440 'initializing': cannot convert from 'const box' to 'box &'
Error (active) E0433 qualifiers dropped in binding reference of type "box &" to initializer of type "const box"
class box
{
public:
int i = 1;
bool operator==(const box& other) const
{
return true;
}
bool operator!=(const box& other) const
{
return !(*this == other);
}
};
namespace std {
template<>
struct hash<box>
{
size_t operator()(const box& boxObject) const
{
return boxObject.i;
}
};
}
int main()
{
std::unordered_set<box> uset;
for (box& b : uset)
{
}
return 0;
}
I'm confused as if I make it a reference to const box
then the problem goes away. If I swap unordered_set
to a vector
then it's not a problem. I'm not sure what is going on here. Can someone help explain it to me. Is this particular to associative containers? I see it also happen with std::set
.