1

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?

Ekalic
  • 683
  • 6
  • 14
  • 5
    you could add a "using std::sqrt;" inside your namespace so that the function lookup doesn't hit your sqrt function and then stop looking. Or you could get rid of the using namespace std and always specify std::sqrt when that's the one you mean. "correct" is harder to define because it assumes someone knows what your intent is. Personally, unless it's just a quick hack, I try to avoid "using namespace" statements and only pull in what I need. – Charlie Feb 13 '15 at 09:39

2 Answers2

3

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);
}
vincentp
  • 1,433
  • 9
  • 12
  • It slightly alarms me that this answer has up votes, you're promoting ambiguous coding styles. – abcthomas Feb 13 '15 at 09:57
  • 1
    @abcthomas, take a look at how `std::swap` is intended to be used. This is a perfectly valid way to support calling an overloaded function and not care about the type (aka static polymorphism). – Jonathan Wakely Feb 13 '15 at 10:05
2

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);
}
Community
  • 1
  • 1
abcthomas
  • 131
  • 7