aantron / better-enums

C++ compile-time enum to string, iteration, in a single header file
http://aantron.github.io/better-enums
BSD 2-Clause "Simplified" License
1.67k stars 173 forks source link

Enum comparison without a + operator #82

Open yan-zaretskiy opened 4 years ago

yan-zaretskiy commented 4 years ago

Is it possible to avoid the plus operator for the comparisons between an Enum and Enum::_enumerated?

yan-zaretskiy commented 4 years ago

I tried to define

bool operator==(MyEnum left, MyEnum::_enumerated right) {
  return left._to_integral() == right;
}

This seems to work. Am I thinking along the correct lines?

aantron commented 4 years ago

Every way I know (knew) of avoiding the + operator had the side effect of introducing ambiguous overload resolution elsewhere. See comments here:

https://github.com/aantron/better-enums/issues/23#issuecomment-231207964 https://github.com/aantron/better-enums/issues/13#issuecomment-160879286

I grant that I may have missed something. Have you run the tests with your modification?

yan-zaretskiy commented 4 years ago

Hmm, trying to build tests complains about the absence of the cxxtest/tests.cc file... Nevermind, install cxxtest...

yan-zaretskiy commented 4 years ago

All errors I see are in the 101-special-values.cc file where you define the invalid_t and default_t types, other tests can be built and they pass.

yan-zaretskiy commented 4 years ago

So, just for the reference, cause I don't really know what I'm doing, I added the following lines:

BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_                                    \
inline bool operator ==(const Enum &a, const Enum::_enumerated &b)             \
    { return a._to_integral() == b; }                                          \
                                                                               \
BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_                                    \
inline bool operator ==(const Enum::_enumerated &a, const Enum &b)             \
    { return a == b._to_integral(); }                                          \
                                                                               \
BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_                                    \
inline bool operator !=(const Enum &a, const Enum::_enumerated &b)             \
    { return a._to_integral() != b; }                                          \
                                                                               \
BETTER_ENUMS_UNUSED BETTER_ENUMS_CONSTEXPR_                                    \
inline bool operator !=(const Enum::_enumerated &a, const Enum &b)             \
    { return a != b._to_integral(); }                                          \