C ++ using-declaration with enums: how to import all elements of an enum?

Here is 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 is giving me a syntax error. I would like to use names N::A

, N::B

, N::C

and N::D

in the main function namespace without a qualifier N::

. But I don't want to do the following two things.

(1) I don't want to talk using namespace N

because this will import everything else in N.

(2) I don't mean to say using N::A

, using N::B

etc. for each member of the enumeration. Because if I want to change the enum, I will have to change my main function as well. Not to mention, the extra workload is tedious and error prone.

I tried to find an answer myself but couldn't. Any help is appreciated.

+3


source to share


2 answers


If you can change the title where it is E

defined try the built-in namespace .

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

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

      



All names in the inline namespace are visible in the enclosing namespace N

as if the inline namespace was not there, but this allows you to import all the names and just the names you want.

+6


source


Use a qualified name

E e = E::A;

      



for example

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

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

    return 0;
}

      

0


source







All Articles