enum-flags icon indicating copy to clipboard operation
enum-flags copied to clipboard

operator~ behaviour

Open NikolausDemmel opened this issue 5 years ago • 2 comments

The ~ operator negates the underlying integer value and something like ~Flags(empty) is thus in general not equal to or-ing all flags.

See an example here: https://wandbox.org/permlink/RQGdNMjBO0RE2tDy

Is there a way this can be fixed? I guess somehow the maximum Flag value would need to be determined somehow...

NikolausDemmel avatar Mar 12 '19 00:03 NikolausDemmel

Indeed, you are correct. The possible solution that I see is

  1. Add a trait that establishes the value of the underlying type that corresponds to all flags set. By default the trait would not be defined.
  2. Only enable operator~ if that trait is defined.
  3. Implement operator~ like this:
template
  < class E
  , class = std::enable_if_t<detail::has_all_flags_set<E>::value>
  >
constexpr auto flags<E>::operator~(flags fl) noexcept -> flags {
  return flags(detail::all_flags_set<E>::value & ~fl.val_);
}

Note, that this would be a breaking change.

grisumbras avatar Mar 12 '19 06:03 grisumbras

Thanks for the quick response. This sounds very reasonable.

Additionally the might be a runtime assert that every flag ever used is a subset of the "all flags" constant. Can be disabled for release build. That might help avoiding inadvertently forgetting to update it.

NikolausDemmel avatar Mar 13 '19 12:03 NikolausDemmel