I have several scoped enums that can be used as bitwise flags. I've implemented the bitwise operator overloads identically for every type as exampled here:
ScopedEnumFoo& operator|=(ScopedEnumFoo& a, const ScopedEnumFoo& b) noexcept {
using underlying = std::underlying_type_t<ScopedEnumFoo>;
auto underlying_a = static_cast<underlying>(a);
auto underlying_b = static_cast<underlying>(b);
a = static_cast<ScopedEnumFoo>(underlying_a | underlying_b);
return a;
}
ScopedEnumFoo operator|(ScopedEnumFoo a, const ScopedEnumFoo& b) noexcept {
a |= b;
return a;
}
ScopedEnumFoo& operator&=(ScopedEnumFoo& a, const ScopedEnumFoo& b) noexcept {
using underlying = std::underlying_type_t<ScopedEnumFoo>;
auto underlying_a = static_cast<underlying>(a);
auto underlying_b = static_cast<underlying>(b);
a = static_cast<ScopedEnumFoo>(underlying_a & underlying_b);
return a;
}
ScopedEnumFoo operator&(ScopedEnumFoo a, const ScopedEnumFoo& b) noexcept {
a &= b;
return a;
}
Other than the scoped enum's type, the code is identical for every type that needs to be used as a flag-ish type. This causes code quality checkers to throw hissy fits that I've duplicated code a dozen (or more) times.
How would I go about "de-duplicating" the code? Is it even possible?
As Jason Turner recently put it:
'I will not copy-paste code' is the single most important thing you can do to write good code...