在以前的代码库中我有:
namespace E {
enum { a, b }
void foo();
}
我想重构为使用枚举类
:
enum class E : int { a, b }
namespace E {
void foo();
}
但是编译失败,因为现在 namespace E
不能使用,因为它与 enum
同名。
有没有解决的办法 ?
基本上我仍然希望调用代码按原样编译,它使用 E::foo()
或 E::a
最佳答案
另一种方法是定义一个枚举类,然后将其值映射到相应的常量:
namespace E {
enum class MyEnum { a, b };
constexpr auto a = MyEnum::a;
constexpr auto b = MyEnum::b;
void foo() {}
}
https://godbolt.org/z/zY5v3G
这种方式将引入强类型检查,并且不必更改依赖代码。更多输入,但不需要 C++20,它将与 C++11 一起工作。
https://stackoverflow.com/questions/65708047/
相关文章:
python - 如何连接来自 3 个小整数的字节以生成由 Python 中的这些字节表示的更大数字
amazon-web-services - `amplify push` 失败 - 属性 : Str
c# - 使用 MVVM 绑定(bind) : Property not found in Xama
react-native - react native : Refresh Controll not
python - 如何从时间序列数据中选择前 n 列而不是在 pandas 中使用 nlargest