C++ allows us to make union class type without any data members. (cppreference even contain an example with it.)
Can one request the compiler to provide default implementation of equality comparison operator for such types? (It can be necessary for some generic code requiring comparison of objects.)
This program:
union U {
constexpr bool operator ==(const U&) const = default;
};
// error in MSVC
bool a = ( U{} == U{} );
// error in Clang
constexpr bool b = ( U{} == U{} );
makes the compilers diverge:
- Visual Studio's compiler implicitly deletes
operator ==:
error C2280: 'bool U::operator ==(const U &) const': attempting to reference a deleted function
note: see declaration of 'U::operator =='
note: 'bool U::operator ==(const U &) const': function was implicitly deleted because 'U' is a union-like class
error C2088: built-in operator '==' cannot be applied to an operand of type 'U'
- Clang defines the operator, but it does not permit using it in constant expressions:
note: pointer to temporary is not a constant expression
note: temporary created here
9 | constexpr bool b = ( U{} == U{} );
- GCC and EDG do not see any error and accept the program. Online demo: https://gcc.godbolt.org/z/WdqGYG4r1
Which implementation is correct here?
unionis very similar to emptystruct, but it has some interesting properties like it cannot be a base class, which is something one wants to prevent sometimes.