Can enum class be nested?

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

Can this be done?

enum A
{
    enum B
    {
        SOMETHING1,
        SOMETHING2
    };

    enum C
    {
        SOMETHING3,
        SOMETHING4
    };
};
         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 18:22

    MESONS pi = PI();
    MATTER mat = pi;
    assert (pi == mat);
    

    Do you mind a little C++11 template magic?

    template 
    struct is_defined_in : std::false_type {};
    
    template 
    struct is_defined_in : is_defined_in {};
    
    template 
    struct is_defined_in : std::true_type {};
    
    template  struct helper {
      friend bool operator==(helper a, helper b)
      { return a.id == b.id; }
      friend bool operator!=(helper a, helper b)
      { return a.id != b.id; }
    
      int id=ID;
    };
    template  struct category {
      int id;
    
      template ::value>::type>
      category(T t) : id(t.id) {}
    
      friend bool operator==(category a, category b)
      { return a.id == b.id; }
      friend bool operator!=(category a, category b)
      { return a.id != b.id; }
    };
    
    enum class ElementaryParticleTypesID
    { PI, PROTON, NEUTRON, ELECTRON };
    
    struct PI       : helper<(int)ElementaryParticleTypesID::PI> {};
    struct PROTON   : helper<(int)ElementaryParticleTypesID::PROTON> {};
    struct NEUTRON  : helper<(int)ElementaryParticleTypesID::NEUTRON> {};
    struct ELECTRON : helper<(int)ElementaryParticleTypesID::ELECTRON> {};
    
    using MESONS = category;
    using BARYONS = category;
    using LEPTONS = category;
    
    using MATTER = category;
    

    (the static_assert currently doesn't work beyond two hierarchies, but this can be added if you want to)

提交回复
热议问题