首页 > 解决方案 > 是否可以在 C++ 中创建可重新定义的命名空间别名?

问题描述

我想创建一个可以全局更改的命名空间别名,以在运行时引用不同的范围。考虑一下:

#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;
}

现在,上面的代码确实可以编译,但我期望得到的不是输出:

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

我得到这个输出:

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

似乎在尝试重新定义时namespace scopeTarget,C++ 只会使用最本地的别名定义,而不是覆盖全局别名。有谁知道在这里实现我的目标的解决方法?

标签: c++namespacesalias

解决方案


您不能在运行时更改命名空间。函数指针会达到预期的效果。

对于命名空间,请参阅:重命名命名空间

对于函数指针,我发现这很有用:https ://www.learncpp.com/cpp-tutorial/78-function-pointers/


推荐阅读