I currently have this:
struct Foo {
int value = 12;
Foo(int a) : value(a) {}
};
and I am trying to do this:
std::map<Foo,int> m{
{{1}, 2}
};
Why is the above giving the compile error:
error: invalid operands to binary expression ('const Foo' and 'const Foo')
>Solution :
When I compile the code you provided with g++, I get a different (and self-explanatory) error:
/usr/include/c++/12/bits/stl_function.h: In instantiation of ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Foo]’:
/usr/include/c++/12/bits/stl_function.h:408:20: error: no match for ‘operator<’ (operand types are ‘const Foo’ and ‘const Foo’)
Since you are using Foo as the key in a sorted container, you must tell the compiler how to compare one Foo to another.
For example, adding this method makes it compile:
bool operator<(const Foo& lhs, const Foo& rhs) {
return lhs.value < rhs.value;
}
Or, if you are using C++20, you can simply add a defaulted three-way comparison to the struct to define all comparison operators:
friend auto operator<=>(const Foo&, const Foo&) = default;