Search code examples
c++namespacesc-preprocessoridentifier

Replacing scoped identifier with preprocessor #define


I want to declare the type of an object based on a preprocessor define. The problem is that the object type is qualified with namespaces:

OldNamespace1::OldNamespace2::OldClass MyObject;

Now when __unit_test is defined I want the compiler to see instead:

NewNamespace1::NewNamespace2::NewClass MyObject;

I have the source for OldClass but I don't own anything in OldNamespace1. I know I can do this obviously with #ifdef conditional includes, but this will require many #ifdef throughout the code. Is there a way to do it with just one (possibly compound) #define?


Solution

  • You might be able to define a namespace like this:

    #ifdef __unit_test
    namespace myns = NewNamespace1::NewNamespace2;
    class myclass : public NewClass {};
    #else
    namespace myns = OldNamespace1::OldNamespace2;
    class myclass : public OldClass {};
    #endif
    

    Now you can simply define your objects via:

    myns::myclass MyObject;