我有几个可以用作按位标志的作用域枚举。我已经为每种类型相同地实现了按位运算符重载,如下例所示:
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;
}
除了有作用域的枚举类型外,对于需要用作标记类型的每种类型,代码都是相同的。这导致代码质量检查人员抛出我已经重复打了十二次(或更多)代码的虚假信息。
我将如何“重复删除”代码?甚至有可能吗?
如Jason Turner recently所说:
“我不会复制粘贴代码”是编写好的代码所能做的最重要的事情...