c++c++11enum-class

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.


Solution

  • There is (still) no way of doing this (in 2023). The closest you can get is to define everything in a long list inside one enum.

    enum class A{
      PARTICLE_MATTER_BARYON_PROTON,
      PARTICLE_MATTER_BARYON_NEUTRON,
      PARTICLE_ANTIMATTER_BARYON_PROTON // etc
    };