c++ - 是否可以在 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++ 只会使用最本地的别名定义,而不是覆盖全局别名。有谁知道在这里实现我的目标的解决方法?
解决方案
您不能在运行时更改命名空间。函数指针会达到预期的效果。
对于命名空间,请参阅:重命名命名空间
对于函数指针,我发现这很有用:https ://www.learncpp.com/cpp-tutorial/78-function-pointers/
推荐阅读
- node.js - 抛出新的 ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
- c - 带有 makefile 和多个 .c 源文件的“未定义引用”
- javascript - Node.js 以管理员身份启动程序
- swiftui - 如何在 SwiftUI 上推送到 DatePicker 选择更改的另一个视图
- java - 构建标准 API 查询以避免 MultipleBagFetchException
- python - 继续尝试安装 ecapture 但每次都给我错误
- c - C 在函数原型中使用宏结构
- python - 循环直到按键被按下并重复
- python - 如何根据出现来排列 Dataframe 值
- c# - 以百分比/概率在 Unity 中生成随机游戏对象