'global scope enum and namespace conflict

I have an ATL COM service and in the .IDL file, I've declared an enum like so:

In Gourmet.idl

typedef enum Food
{
    Chocolate = 0,
    Doughnut,
    HotDog
} Food;

A header file is automatically generated, creating Gourmet_i.h.

In another .CPP file (let's just call it Decadence.cpp) of the same ATL COM project, I #include Gourmet_i.h. I've implemented a class in this .CPP and it's under the namespace 'Chocolate'.

For example in Decadence.cpp:

#include "Gourmet_i.h"

namespace Chocolate {

// Constructor
void Decadence::Decadence() {}

// ... and so on

} // namespace Chocolate

When compiled I get the following error about Gourmet_i.h:

error C2365: 'Chocolate': redefinition; previous definition was 'namespace'

I see this occurs because the enum for the IDL is defined in the global namespace, but is it possible to contain this definition -- so it doesn't pollute the global namespace -- and I wouldn't have this conflict?



Solution 1:[1]

Short of renaming the namespace or enum member about the only solution for this is to wrap the contents of the generated header file in a namespace. This is not without pitfalls and depending on how the contents of your MIDL file it may eventually cause a few headaches. The cleanest way that I can see would be to create a proxy header file that declares the namespace then includes the MIDL generated header file.

Gourmet.h

namespace MIDLStuff
{
    #include "Gourmet_i.h"
}

Solution 2:[2]

If you are using C++11 you can use Scoped Enumeration by including class:

typedef enum class Food
{
    Chocolate = 0,
    Doughnut,
    HotDog
} Food;

Now you need to write Food::Chocolate when using the value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2