[英]C++ namespace name hiding
Suppose this piece of code: 假设这段代码:
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 ::
}
Is there a way how to call std::sqrt inside abc namespace without ::? 有没有一种方法可以在没有::的abc名称空间中调用std :: sqrt? In my project, I was originally not using namespaces and so all overloaded functions were visible.
在我的项目中,我最初没有使用名称空间,因此所有重载函数都是可见的。 If I introduce namespace abc it means that I have to manually check all functions that are hidden by my overload and add ::
如果我引入名称空间abc,则意味着我必须手动检查重载隐藏的所有函数并添加::
What is the correct way to handle this problem? 解决此问题的正确方法是什么?
I tried this and it works fine: 我试过了,它工作正常:
namespace abc {
void sqrt(SomeType x) {}
using std::sqrt;
float x = 1;
float y1 = sqrt(x);
float y2 = sqrt(x);
}
Generally using namespace std
is considered bad practice : Why is "using namespace std" considered bad practice? 通常,
using namespace std
被认为是不好的做法: 为什么“使用命名空间std”被认为是坏习惯?
It is good practice to be as explicit as possible, so by specifying std::sqrt()
there is absolutely no confusion over which function you're actually calling. 最好是尽可能地明确,因此通过指定
std::sqrt()
绝对不会混淆您实际上在调用哪个函数。 eg 例如
namespace abc
{
void sqrt(SomeType x) {}
float x = 1;
float y1 = sqrt(x);
float y2 = std::sqrt(x);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.