【发布时间】:2020-07-15 02:09:04
【问题描述】:
我有几个可以用作按位标志的作用域枚举。我已经为每种类型实现了相同的位运算符重载,如下所示:
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 所说:
“我不会复制粘贴代码”是您编写好代码所能做的最重要的事情......
【问题讨论】:
标签: c++ enums code-duplication scoped-enums