In the following program, struct A has default friend equality comparison operator, which is redeclared again to get the pointer of the function (&operator==):
struct A {
friend constexpr bool operator ==(const A &, const A &) noexcept = default;
};
static_assert( A{} == A{} ); //if this line is removed the program fails
constexpr bool operator ==(const A &, const A &) noexcept;
static_assert( (&operator==)( A{}, A{} ) );
All major compilers (GCC, Clang, MSVC) are fine with the program. Online demo: https://gcc.godbolt.org/z/dhcd8esKn
However if the line with static_assert( A{} == A{} ); is removed, then the same compilers start rejecting the program with the errors:
error: 'constexpr bool operator==(const A&, const A&)' used before its definition
note: undefined function 'operator==' cannot be used in a constant
note: failure was caused by call of undefined function or one not declared 'constexpr'
Could you please explain why above program is valid only in presence of static_assert( A{} == A{} ); before operator== redeclaration?
=defaultdoes not get instantiated until needed. The first static_assert forces it to be generated, so then it has an address, and therefore the second static_assert can take its address. But I am not a language lawyer, so I hope one of them will chime in and demystify this puzzle.