C++命名空间名称隐藏
C++ namespace name hiding
假设这段代码:
using namespace std;
namespace abc {
void sqrt(SomeType x) {}
float x = 1;
float y1 = sqrt(x); // 1) does not compile since std::sqrt() is hidden
float y2 = ::sqrt(x); // 2) compiles bud it is necessary to add ::
}
有没有一种方法可以在abc命名空间内调用std::sqrt而不使用::?在我的项目中,我最初不使用名称空间,所以所有重载的函数都是可见的。如果我引入名称空间abc,这意味着我必须手动检查所有被重载隐藏的函数,并添加::
处理这个问题的正确方法是什么?
我试过了,效果很好:
namespace abc {
void sqrt(SomeType x) {}
using std::sqrt;
float x = 1;
float y1 = sqrt(x);
float y2 = sqrt(x);
}
通常using namespace std
被认为是不好的做法:为什么"使用命名空间std";被认为是不好的做法?
尽可能明确是一种很好的做法,因此通过指定std::sqrt()
,绝对不会混淆实际调用的函数。例如
namespace abc
{
void sqrt(SomeType x) {}
float x = 1;
float y1 = sqrt(x);
float y2 = std::sqrt(x);
}
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 在命名空间中定义函数还是限定函数
- C++:对不存在的命名空间使用命名空间指令
- 通过继承类使用来自不同命名空间的运算符
- 使用命名空间时出现多个定义错误
- CUDA内核和数学函数的显式命名空间
- 嵌套的匿名命名空间
- CMakeLists.txt中的命名空间表示法
- 类是C++中的命名空间吗
- c++ 内联友元函数是否会导致命名空间之间的名称隐藏?
- C++命名空间名称隐藏
- 在C++中隐藏命名空间
- 为什么运算符 " " 隐藏在命名空间中?
- 在我的命名空间中隐藏 DirectX 命名空间
- 隐藏第三方命名空间是否危险
- 隐藏模板化的辅助函数——静态成员或未命名的命名空间
- 在命名空间之外隐藏类成员
- 在c++中从父命名空间访问隐藏操作符
- 命名空间作用域中的操作符在全局作用域中隐藏另一个操作符