Three-way comparison of pointer to functions fails

Viewed 222

Why can't I compare pointers to functions with GCC trunk?

using f_t = int(*)(int);
f_t a { nullptr }, b { nullptr };
auto c = a <=> b;

int main (){}

gives

a.cpp:4:13: error: invalid operands of types ‘f_t’ {aka ‘int (*)(int)’} and ‘f_t’ {aka ‘int (*)(int)’} to binary ‘operator<=>’
    4 | auto c = (a <=> b) == 0;
      |           ~ ^~~ ~
      |           |     |
      |           |     f_t {aka int (*)(int)}
      |           f_t {aka int (*)(int)}

1 Answers

The result of using normal relational operators on function pointers is unspecified if the pointers are unequal. You can compare pointers to objects (but only meaningfully if they're pointers into the same array or structure), but relating function pointers isn't really viable.

Rather than taking the sometimes-unspecified route, C++20 simply forbids using <=> for non-object pointers.

You can test for equality between such pointers, but not their relative ordering. If you absolutely need to do this for some reason, you can cast the pointers to void*s and use std::less<> for such comparisons.

Related