1

假设这段代码:

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 这意味着我必须手动检查所有被我的重载隐藏的函数并添加 ::

处理这个问题的正确方法是什么?

4

2 回答 2

3

我试过了,效果很好:

namespace abc {
    void sqrt(SomeType x) {}
    using std::sqrt;

    float x = 1;
    float y1 = sqrt(x);
    float y2 = sqrt(x);
}
于 2015-02-13T09:37:21.807 回答
2

通常using namespace std被认为是不好的做法:为什么“使用命名空间标准”被认为是不好的做法?

最好的做法是尽可能明确,因此通过指定std::sqrt()绝对不会混淆您实际调用的函数。例如

namespace abc
{
   void sqrt(SomeType x) {}

   float x = 1;
   float y1 = sqrt(x);
   float y2 = std::sqrt(x);
}
于 2015-02-13T09:55:25.083 回答