Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration of nested enum

I have code similar to the following:

class B
{
}

class A
{
  enum {
     EOne,
     ETwo
  } EMyEnum;

  B myB;
}

I want to declare a member of type EMyEnum in class B (which is declared before A). Is this possible? I realise the solution is to declare class B second, but for clarity I would prefer not to.

like image 307
MM. Avatar asked Feb 10 '10 15:02

MM.


People also ask

Can I forward declare an enum?

Because enum definitions cannot reference one another, and no enum definition can cross-reference another type, the forward declaration of an enumeration type is never necessary. To make the code valid, you can always provide the full definition of the enum before it is used.

What is the type of enum in C++?

The type of a C++ enum is the enum itself. Its range is rather arbitrary, but in practical terms, its underlying type is an int . It is implicitly cast to int wherever it's used, though.


1 Answers

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!

like image 182
Matthieu M. Avatar answered Sep 20 '22 14:09

Matthieu M.