Workarounds for the problem of class recoding forward?

I maintain a large code base and use a combination of forward declarations and the pImpl idiom to save compilation time and reduce dependencies (and this works very well)

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

// 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 am looking for ways to avoid this and can only think of the following:

Move class enumerations to a separate type 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 listing

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

What did I miss? How other people will manage this restriction (not being able to forward the declaration of transfers.)

+4
source share
3 answers

Put the enumeration in your own type:

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

Then Foo and Bar can both access FooEnum::Type and Bar.h not include Foo.h

+2
source

Put the enumeration in the class containing the PIMPL.

+3
source

I would say that enumerations are a bad idea to start with, but in general for constants / many things like constants in C ++, none of which are completely constant, and all of which have problems. I like to put it in a structure, and then classes using it inherit from the structure.

I also claim that the idiom pimpl is bad. Actually, I'm sure this is a bad way to do something. This is what works, but uncomfortable and a little stupid. It is also easy to avoid, and the only reason it occurs is people who use other bad design options.

Usually, someone simply puts things on the OOP class, which they are intended for a particular. Then you get a case of mixed inheritance and a lot of problems that it causes, for example, super slow compilation time. Instead, consider pure virtual base classes, and then create your libraries to avoid patterns and avoid the direct declaration problem. Not for everyone, but definitely for cases where you generate code for many classes.

0
source

All Articles