Can enum class be nested?

后端 未结 4 1414
执笔经年
执笔经年 2021-02-14 17:33

Can this be done?

enum A
{
    enum B
    {
        SOMETHING1,
        SOMETHING2
    };

    enum C
    {
        SOMETHING3,
        SOMETHING4
    };
};
         


        
4条回答
  •  礼貌的吻别
    2021-02-14 18:09

    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.

提交回复
热议问题