是否可以在C ++中创建可重新定义的名称空间别名?

时间:2019-04-10 02:39:23

标签: c++ namespaces alias

我想创建一个名称空间别名,可以在运行时对其进行全局更改以引用不同的作用域。考虑一下:

#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 ++将仅使用最本地的别名定义,而不是覆盖全局别名。  有人知道在这里可以实现我的目标的解决方法吗?

1 个答案:

答案 0 :(得分:0)

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

有关名称空间,请参见:Renaming namespaces

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