I am trying to assign a custom type as a key for std::map
. Here is the type which I am using as key:
struct Foo
{
Foo(std::string s) : foo_value(s){}
bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; }
bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; }
std::string foo_value;
};
When used with std::map
, I am getting the following error:
error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:program filesmicrosoft visual studio 8vcincludefunctional 143
If I change the struct
to the one below, everything works:
struct Foo
{
Foo(std::string s) : foo_value(s) {}
friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value; }
friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value; }
std::string foo_value;
};
Nothing changed, except that the operator is overloaded as friend. Why does my first code not work?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…