I wanted to create a std::set<X>
, for a pod struct, X
.
I tried providing a free operator<
.
I did not want this operator to have a global effect (outside this compilation unit),
so I set the operator<
as static. (link to code)
struct X { int value; };
static bool operator< (const X& a, const X& b) { return a.value < b.value; }
void foo() {
std::set<X> some_set;
some_set.insert({1});
}
This compiles fine.
However, if I move the operator<
in an unnamed namespace (link to code)
struct X { int value; };
namespace {
bool operator< (const X& a, const X& b) { return a.value < b.value; }
}
void foo() {
std::set<X> some_set;
some_set.insert({1});
}
which should be equivalent,
then std::less<X>
complains:
usr/local/include/c++/12.1.0/bits/stl_function.h:408:20: error: no match for 'operator<' (operand types are 'const X' and 'const X')
{ return __x < __y; }
Okay, I could have used a custom comparator instead.
But can anybody explain why the above does not work? In general, is it possible to provide a different operator implementation in compilation units of the same struct?