C++ – Can Enum Class Be Nested?

c++c++11enum-class

Can this be done?

enum A
{
    enum B
    {
        SOMETHING1,
        SOMETHING2
    };

    enum C
    {
        SOMETHING3,
        SOMETHING4
    };
};

If not is there an alternative solution?

The purpose of this question: Want/need to be able to do something like this:

enum class ElementaryParticleTypes
{

    enum class MATTER
    {
        enum class MESONS
        {
            PI
        };

        enum class BARYONS
        {
            PROTON,
            NEUTRON
        };

        enum class LEPTONS
        {
            ELECTRON
        };
    };

    enum class ANTI_MATTER
    {
        enum class ANTI_MESONS
        {
            ANTI_PI
        };

        enum class ANTI_BARYONS
        {
            ANTI_PROTON
            ANTI_NEUTRON
        };

        enum class ANTI_LEPTONS
        {
            POSITRON
        };
    };

};

Wish to use the strongly-typed capabilities.

Best Answer

No, they cannot be nested that way. In fact, any compiler would reject it.

If not is there an alternative solution?

That mostly depends on what you are trying to achieve (solution to what problem?). If your goal is to be able to write something like A::B::SOMETHING1, you could just define them within a namespace, this way:

namespace A
{
    enum B
    {
        SOMETHING1,
        SOMETHING2
    };

    enum C
    {
        SOMETHING3,
        SOMETHING4
    };     
}
Related Question