Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enum class be nested?

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.

like image 607
FreelanceConsultant Avatar asked Feb 24 '13 21:02

FreelanceConsultant


2 Answers

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
    };     
}
like image 148
Andy Prowl Avatar answered Oct 25 '22 05:10

Andy Prowl


Seeing that in this particular case, the enumerations aren’t likely to change often, you could go for:

namespace ParticleTypes {
    namespace Matter {
        enum Mesons {
            Pi
        };

        enum Baryons {
            Proton = Pi + 1,
            Neutron
        };

        enum Leptons {
            Electron = Neutron + 1
        };
    }

    namespace AntiMatter {
        enum AntiMesons {
            AntiPi = Matter::Electron + 1
        };

        // ...
    }
}

I do wonder, however, why you want different enum types for different types of particles. Do you have functions which accept an argument of type Mesons, but not of type Leptons? If not, and all your functions accept any of the particles, then use a single enum – and preferably, drop the long prefixes to the names of the values like MATTER_MESONS_, MATTER_BARYONS_ etc.

like image 27
Lumen Avatar answered Oct 25 '22 05:10

Lumen