In previous codebase I have:
namespace E {
enum { a, b }
void foo();
}
I want to refactor to using enum class
:
enum class E : int { a, b }
namespace E {
void foo();
}
However this fails to compile because now namespace E
can't be used as it has same name as enum
. Is there a way around this? Basically I still want that the calling code compile as-is, which is using either E::foo()
or E::a
Other way to do that is define an enum class and then map its values to respective constants:
namespace E {
enum class MyEnum { a, b };
constexpr auto a = MyEnum::a;
constexpr auto b = MyEnum::b;
void foo() {}
}
This way strong type checking will be introduced and depending code will not have to be altered. More typing, but doesn't require C++20, it will work with C++11.
Basically I still want that the calling code compile as-is, which is using either E::foo() or E::a
No, you cannot do that, one of the advantages of enum class
is not polluting the outer namespace. The other is no implicit conversions.
Starting with C++20 it is possible to explicitly request the name injection with using enum E;
enum class E : int { foo, bar };
using enum E;
int main()
{
E x = foo; // Now works
E y = E::bar; // Still works
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.