C++命名空间名称隐藏

C++ namespace name hiding

本文关键字:隐藏 命名空间 C++      更新时间:2023-10-16

假设这段代码:

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);
}