This doesn't work:
struct A {
int x1;
int x2;
};
int main() {
int A::*p1 = &A::x1;
set<int A::*> s;
s.insert( p1 ); // compile error: No operator<
unordered_set<int A::*> us;
us.insert( p1 ); // compile error: No hash function
}
I have to provide either a comparison function (for set
) or a hash function (for unordered_set
). The only way I figured out so far would involve checking the raw bytes underlying the member pointers:
struct XLess {
bool operator()( int A::* a, int A::*b ){
return memcmp( &a, &b, sizeof(a) ) < 0;
}
};
set<int A::*, XLess> s; // now appears to work
Is this a reliable way to create a set? It depends on identical pointers being represented by identical bytes. Is there a better solution to this?