C ++ Comparing member function pointers

In C ++, is it possible to define sort order for pointers to member functions? The operator seems to be <undefined. Also, it is illegal to pour in void *.

class A { public: void Test1(){} void Test2(){} }; int main() { void (A::* const one)() = &A::Test1; void (A::* const two)() = &A::Test2; bool equal = one == two; //Equality works fine. bool less = one < two; //Less than doesn't. return 0; } 

Thanks!

+4
source share
2 answers

Function pointers are not comparable with C ++. Equalization is supported, except in situations where at least one of the pointers actually points to a virtual member function (in this case, the result is not specified).

Of course, you can always enter order by implementing a comparison predicate and explicitly matching pointers (it won't look too elegant, since you can use comparison comparisons). Other possible solutions would cross the territory of various implementation-specific hacks.

+5
source

Member function pointers are not actual pointers. You should look at them as opaque structures. What the method pointer contains:

  struct method_pointer { bool method_is_virtual; union { unsigned vtable_offset; // for a virtual function, need the vtable entry void* function_pointer; // otherwise need the pointer to the concrete method } }; 

If you can apply this to void * (you cannot), all you have is a pointer to a structure, not a pointer to a code. Therefore, the <() operator is undefined, since the value of the struct pointer is always where it occurs in memory.

In addition to this, what do you sort by?

+2
source

All Articles