Forward declaration of nested enum

后端 未结 3 775
傲寒
傲寒 2020-12-17 14:50

I have code similar to the following:

class B
{
}

class A
{
  enum {
     EOne,
     ETwo
  } EMyEnum;

  B myB;
}

I want to declare a mem

相关标签:
3条回答
  • 2020-12-17 15:13

    It's not possible... but it can be faked with inheritance abuse :)

    namespace detail
    {
      class A_EMyEnum
      {
      public:
        enum {
           EOne,
           ETwo
        } EMyEnum;
    
      protected:
        A_EMyEnum() {}
        A_EMyEnum(const A_EMyEnum&) {}
        A_EMyEnum& operator=(const A_EMyEnum&) { return *this; }
        ~A_EMyEnum() {}
      }; // class A_EMyEnum
    } // namespace detail
    
    class B { // use detail::A_EMyEnum };
    
    class A: public detail::A_EMyEnum
    {
    
      B mB;
    };
    

    On the other hand... why don't you simply forward declare B ?

    class B;
    
    class A
    {
    public:
      enum EMyEnum {};
    
      A();
      A(const A&);
      A& operator=(const A&);
      ~A();
      void swap(A&);
    
    private:
      B* mB;
    };
    
    class B { // use A::EMyEnum };
    

    Sure you need to actually write all the normally "default generated" methods of A, but hey that does not cost so much!

    0 讨论(0)
  • 2020-12-17 15:16

    You can declare A as template paramater of B. Second way to solve it is using int - it is known that c++ enum is int.

    0 讨论(0)
  • 2020-12-17 15:20

    The current C++ standard does not allow forward declarations of enums, although they will be coming in the upcoming C++0x standard.

    See here for more info.

    0 讨论(0)
提交回复
热议问题