PDA

View Full Version : Using namespace enums in headers



Phlucious
23rd November 2011, 01:59
Enum types are great in that they enforce certain values and protect functions from receiving values outside of the desired range. I'm trying to encapsulate my enums in a namespace so that they aren't on the global scope, but I'm hitting some issues that I think are related to circular dependencies. Here's some code excerpts.

color_namespace.h

#ifndef COLOR_NAMESPACE_H
#define COLOR_NAMESPACE_H

#include "colorwriter.h"
//#include lots of other headers

namespace CC
{
enum colors_t
{
BLACK = 0,
RED = 1,
BLUE = 2,
GREEN = 4,
WHITE = 8
}
}
#endif
colorwriter.h

#ifdef COLORWRITER_H
#define COLORWRITER_H

#include "color_namespace.h"

class ColorWriter
{
public:
ColorWriter();
virtual bool writeColor(CC::colors_t c);
}
#endif
Now, the problem I'm running into is that I get a compiler error saying that 'CC' has not been declared. My research suggest there's a circular dependency, but how could that be when both headers have include guards? I would like to keep the #include in the namespace because there's a dozen other dependencies and I'd like to enable the user to only have to include one file instead of a dozen.

If the enum was a class, I'd just forward declare it in the .h and #include the namespace in the .cpp, but I can't do that since enums can't be forward declared. Is the value protection provided by an enum simply not possible for functions declared outside that namespace?

Thanks!

^NyAw^
24th November 2011, 11:50
Hi,

Try adding this


using namespace CC;

in colorwriter.h before the class definition.

stampede
25th November 2011, 10:20
I would like to keep the #include in the namespace because there's a dozen other dependencies and I'd like to enable the user to only have to include one file instead of a dozen.
Looks like in this case its enough to include "colorwriter.h" instead of "color_namespace.h".
Just define the enum before any other class, it does not depend on them. My suggestion is to remove the #include "colorwriter.h" (and any other header that uses enum) from color_namespace.h, move the enum definition to separate file and include it in any source file depending on the enum, not the other way around.
Simple fix could be to move the #include directives after enum definition.

Phlucious
30th November 2011, 01:28
Thanks stampede! Both suggestions have proven very useful.

Moving the enum to be before the #defines worked so that I could simply #include the namespace from within any of the files relying on the enums defined within the namespace, while still allowing an end user to #include "color_namespace.h" and maintain full functionality of every feature.

Separating the enum definition into another header to keep things clean also worked, but it meant that I had to #include multiple files instead of just one.