Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring to enum to enum class shadows namespace

Tags:

c++

c++11

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

like image 409
lezebulon Avatar asked Jun 06 '26 00:06

lezebulon


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.

like image 191
Marek R Avatar answered Jun 07 '26 14:06

Marek R


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
}
like image 22
Quimby Avatar answered Jun 07 '26 13:06

Quimby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!