0

I would like to create a namespace alias that can be changed globally to refer to different scopes at runtime. Consider this:

#include <iostream>

namespace scopePrimary {
    int somethingOfInterest = 1;
}
namespace scopeSecondary {
    int somethingOfInterest = 2;
}
namespace scopeTarget = scopePrimary;

int doStuffInTargetScope() {
    using namespace scopeTarget;
    return somethingOfInterest;
}

int main() {
    // Do something with the somethingOfInterest variable defined in scopePrimary
    std::cout << "doStuffInTargetScope():\n" \
    "  somethingOfInterest = " << doStuffInTargetScope() << std::endl;

    namespace scopeTarget = scopeSecondary;
    using namespace scopeTarget;

    // Do something with the somethingOfInterest variable defined in scopeSecondary
    std::cout << "doStuffInTargetScope():\n" \
    "  somethingOfInterest = " << doStuffInTargetScope() << std::endl;

    std::cout << "main():\n  somethingOfInterest = "
    << somethingOfInterest << std::endl;
}

Now, the above code does compile, but instead of getting the output would I expect:

doStuffInTargetScope():
  somethingOfInterest = 1
doStuffInTargetScope():
  somethingOfInterest = 2
main():
  somethingOfInterest = 2

I'm getting this output:

doStuffInTargetScope():
  somethingOfInterest = 1
doStuffInTargetScope():
  somethingOfInterest = 1
main():
  somethingOfInterest = 2

It seems that when trying to redefine namespace scopeTarget, C++ will only use the most local alias definition, instead of overwriting the global alias. Does anyone know a work-around to achieve my goal here?

Enc0der
  • 1
  • 1

1 Answers1

0

You cannot change namespaces at run time. Function pointers would achieve the desired effect.

For namespaces see: Renaming namespaces

For function pointers I found this useful: https://www.learncpp.com/cpp-tutorial/78-function-pointers/

evader110
  • 69
  • 6