Refactoring to enum to enum class shadows namespace

Viewed 109

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

2 Answers

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() {}
}

https://godbolt.org/z/zY5v3G

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
}
Related