Ekalic
Ekalic

Reputation: 703

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?

Upvotes: 1

Views: 867

Answers (2)

abcthomas
abcthomas

Reputation: 123

Generally using namespace stdis 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. e.g.

namespace abc
{
   void sqrt(SomeType x) {}

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

Upvotes: 2

vincentp
vincentp

Reputation: 1433

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

Upvotes: 3

Related Questions