Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using-declaration with enums: how to import all the enum items?

Tags:

c++

enums

using

Here's a code snippet to demonstrate my question.

namespace N{
    enum E { A, B, C, D };
}

int main(){
    using N::E;
    E e = A; // syntax error: 'A' is not declared
}

The last line gives me a syntax error. I'd like to use the names N::A, N::B, N::C and N::D in the main function without the namespace qualifier N::. But I don't want to do the following two things

(1) I don't want to say using namespace N, because that would import everything else in N.

(2) I don't want say using N::A, using N::B, etc for every member of the enum. Because then if I want to modify the enum, I'll have to change my main function as well. Not to mention that the extra typing is tedious and error-prone.

I tried searching for an answer myself but couldn't. Any help is appreciated.

like image 535
HazySmoke Avatar asked Mar 09 '23 19:03

HazySmoke


1 Answers

If you can change the header where E is defined, try an inline namespace.

namespace N {
    inline namespace Enums {
        enum E { A, B, C, D };
    }
}

int main() {
    using namespace N::Enums;
    E e = A;
}

All the names in the inline namespace are visible in the enclosing namespace N as though the inline namespace weren't there, but this allows you to import all the names and just the names you want.

like image 112
aschepler Avatar answered Apr 06 '23 05:04

aschepler