17

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.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
MM.
  • 4,224
  • 5
  • 37
  • 74

3 Answers3

11

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!

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • 1
    Yeah, the latter was what I ended up doing. Just needed to confirm that my preference wasn't possible:) – MM. Feb 12 '10 at 11:07
  • What does `enum {} EMyEnum` mean? I've never come across it before? – Olumide Dec 14 '14 at 02:31
  • @Olumide: It contains two weird nits inherited from C. First, in C you can immediately instantiate a `struct` or `enum`: `struct X { int x; } myX;` declares a variable `myX` of type `X`. Second, in C you can leave off the `struct` or `enum` name and thus create an anonymous type. It is often used on `enum` to declare constants in C: `enum { CONSTANT_A = 12, CONSTANT_B = 42 };` but can also be combined with the first nit to create a variable of an anonymous type. Obviously, in the particular context of this question, this is probably not what is intended... – Matthieu M. Dec 14 '14 at 12:51
2

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.

Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
0

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.

Dewfy
  • 23,277
  • 13
  • 73
  • 121