我想创建一个名称空间别名,可以全局更改以在运行时引用不同的作用域。考虑一下:
#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 ++将只使用最本地的别名定义,而不是覆盖全局别名。有谁知道在这里实现我的目标的解决方案?
您无法在运行时更改名称空间。函数指针将达到预期的效果。
对于名称空间,请参阅:Renaming namespaces
对于函数指针,我发现这很有用:https://www.learncpp.com/cpp-tutorial/78-function-pointers/