I have some code, that has namespace configurable by user as this:
#pragma once
#ifdef GRAPHICS_NAMESPACE
namespace GRAPHICS_NAMESPACE {
#endif
class Foo {
}
#ifdef GRAPHICS_NAMESPACE
}
#endif
And in cpp file, there is
#ifdef GRAPHICS_NAMESPACE
using namespace GRAPHICS_NAMESPACE;
#endif
Now I have a problem. I have defined -DGRAPHICS_NAMESPACE=Graphics
and I have a header with:
#pragma once
#include "Foo.h"
class Bar {
Foo foo;
}
But Foo foo
gives me error, since Foo
is in namespace now named Graphics
. I can solve this with adding
#ifdef GRAPHICS_NAMESPACE
using namespace GRAPHICS_NAMESPACE;
#endif
to my header, but that is not very safe since it will be using namespace everywhere where I include my header. Is there any other solution?
Although I would say this is not the optimal way to arrange things, I've seen worse and the solution to your problem is rather straightforward:
class Bar {
#ifdef GRAPHICS_NAMESPACE
GRAPHICS_NAMESPACE::
#endif
Foo foo;
}
If you insist on sticking with this design, you can clean this up, somewhat, by defining a 2nd macro:
#ifdef GRAPHICS_NAMESPACE
#define GRAPHICS_CLASS(x) GRAPHICS_NAMESPACE:: x
#else
#define GRAPHICS_CLASS(x) x
#endif
And then declare things along the lines of:
class Bar {
GRAPHICS_CLASS(Foo) foo;
}
Finally, if you insist on relying on the preprocessor for this kind of critical functionality, you may want to consider spending a little bit more time reading what your C++ book says on this topic. These are fairly basic, straightforward uses of the C++ preprocessor, which I expect should be fully explained in any introduction on what a C++ preprocessor is, and how it works.