Search code examples
c++enumspimpl-idiom

Workarounds for the forward-declared class enumeration problem?


I am maintaining a large code base and am using a combination of forward declarations and the pImpl idiom to keep compile times down and reduce dependencies (and it works really well,)

The problem I have is with classes that contain public enumerations. These enumerations cannot be forward declared so I am left with no option but to include the class header. For example:

// Foo.h

class Foo
{
public:
  enum Type
  {
    TYPE_A,
    TYPE_B,
  };
  ...
};

// Bar.h

#include "Foo.h" // For Foo::Type

class Bar
{
public:
  void someFunction(Foo::Type type);
  ...
};

So, I'm looking for ways to avoid this and can only think of the following:

Move the class enumerations to a separate 'types' namespace

// FooTypes.h

namespace FooTypes
{
  enum Type
  {
    TYPE_A,
    TYPE_B,
  };
}

// Bar.h

#include "FooTypes.h"

class Bar
{
public:
  void someFunction(FooTypes::Type type);
  ...
};

Use int instead of the enumeration

// Bar.h

class Bar
{
public:
  void someFunction(int type);
  ...
};

What have I missed? How do other people get around this limitation (not being able to forward declare enumerations.)


Solution

  • Put the enumeration into its own type:

    struct FooEnum
    {
      enum Type
      {
        TYPE_A,
        TYPE_B,
      };
    };
    

    Then Foo and Bar can both access FooEnum::Type and Bar.h doesn't need to include Foo.h.