In my C++ header files I try to use forward declarations (class MyClass;) instead of #including the class header, as recommended in many C++ coding standards (the Google C++ Style Guide is one).
Unfortunately, when I introduce enumerations, I can’t do the forward declaration any more. Like this:
//// myclass1.hpp //// class MyClass1 { enum MyEnum1 { Enum_A, Enum_B, Enum_C }; }; //// myclass2.hpp //// // I want to avoid this #include 'myclass1.hpp' // I'd prefer to do this (forward declaration) class MyClass1; class MyClass2 { // This is o.k.: I only need to forward declare MyClass1 MyClass1* ptr; // This forces me to #include, but I don't want to! void func( MyClass1::MyEnum1 e ); };
The best solution I can think of so far is to replace enums with member constants:
//// myclass1.hpp //// MyClass1 { static const int Enum_A; static const int Enum_B; static const int Enum_C; }; //// myclass1.cpp //// const int Enum_A = 1; const int Enum_B = 2; const int Enum_C = 3;
In this case, though, the solution seems worse than the problem.
I’m currently looking through Large Scale C++ Software Design (Lakos) and Working Effectively with Legacy Code (Feathers) for dependency breaking techniques, but I haven’t found a good solution yet.
You cannot forward declare enum values – and your workaround is a step down the path to complete madness.
Are you experiencing any major compilation slowdowns caused by #including headers? If not, just #include them. Use of forward declarations is not ‘best practice’ it is a hack.