Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typedefs and enums

Tags:

c++

I am trying to introduce an alias for an enum in one namespace into another namespace. While I can declare a variable of the aliased type, the compiler (gcc 4.1.2) will not recognize any of the enumeration's values.

namespace A
{
    enum a { One = 1, Two = 2 };
}

namespace B
{
    typedef enum A::a b;
};

A::a a_value = A::One;   // Pretty standard
B::b b_value = B::One;   // Does not work
B::b c_value = A::One;   // Clearly B is a typedef for A

int main (int argc, const char *argv[])
{
   return 0;
}

The compiler error is

test.cc:12: error: 'One' is not a member of 'B'.

like image 443
Jim Russell Avatar asked Jun 13 '13 22:06

Jim Russell


1 Answers

While the enum type is accessible in B through b, the values are not and must be brought in explicitly:

namespace B {
    typedef A::a b;
    using A::One;
}

I don't think there's a way to bring them all in without separate using statements for each unless you do using namespace A; or put the enum in an inline namespace and have a using statement for that. The latter might be preferable if you're worried about bringing in all of A and would still like to use the enum values with just A::value. Here's an example:

namespace A
{
    inline namespace en {
        enum a { One = 1, Two = 2 };
    }

    enum c {Three};
}

namespace B
{
    using namespace A::en;
    typedef A::a b;
}

A::a a_value = A::One; // works; things in en are still visible in A
B::b b_value = B::One; // works; en was brought into B
B::b c_value = A::One; // works
A::c meh = B::Three; //fails; only en was brought into B

Be aware that inline namespaces were introduced in C++11, which GCC 4.1.2 has no support for. If you can, I would strongly recommend upgrading. The latest stable release is 4.8.1.

like image 195
chris Avatar answered Oct 27 '22 03:10

chris