简体   繁体   中英

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 ::? 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 ::

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?

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. eg

namespace abc
{
   void sqrt(SomeType x) {}

   float x = 1;
   float y1 = sqrt(x);
   float y2 = std::sqrt(x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM