M
Michael Klatt
I've just encountered a strange situation (at least to me) regarding
friend operators and member operators:
#include <map>
class Key
{
friend bool operator<(const Key& lhs, const Key& rhs)
{
return lhs.myInt < rhs.myInt;
}
public :
Key(int i) : myInt(i) {}
bool operator<(const Key& rhs)
{
return myInt < rhs.myInt;
}
private :
int myInt;
};
int main()
{
std::map<Key, int> table; // Key must support operator<()
table.insert(std::make_pair(Key(1), 1));
table.insert(std::make_pair(Key(2), 2));
return 0;
}
I assumed that friend operator<(const Key&, const Key&) and member
operator operator<(const Key& rhs) are effectively the same thing, but
the compiler (g++3) doesn't think so. Without the friend operator I
get an error message like "cannot find match for const Key& < const
Key&" generated within the std::map code, but it does say that Key <
const Key& (the member operator) is a near match. Why can't the
compiler treat a Key as a const Key& in this case?
friend operators and member operators:
#include <map>
class Key
{
friend bool operator<(const Key& lhs, const Key& rhs)
{
return lhs.myInt < rhs.myInt;
}
public :
Key(int i) : myInt(i) {}
bool operator<(const Key& rhs)
{
return myInt < rhs.myInt;
}
private :
int myInt;
};
int main()
{
std::map<Key, int> table; // Key must support operator<()
table.insert(std::make_pair(Key(1), 1));
table.insert(std::make_pair(Key(2), 2));
return 0;
}
I assumed that friend operator<(const Key&, const Key&) and member
operator operator<(const Key& rhs) are effectively the same thing, but
the compiler (g++3) doesn't think so. Without the friend operator I
get an error message like "cannot find match for const Key& < const
Key&" generated within the std::map code, but it does say that Key <
const Key& (the member operator) is a near match. Why can't the
compiler treat a Key as a const Key& in this case?