c++ - 为什么使用 std::swap 不会隐藏外部作用域中的其他交换函数

标签 c++ namespaces hide overloading swap

在 C++ Primer 5 中,第 13.3 节:

Very careful readers may wonder why the using declaration inside swap does not hide the declaration for the HasPtr version of swap (6.4.1). We'll explain the reasons for why this code works in 18.2.3.

示例代码如下:

void swap(HasPtr &lhs, HasPtr &rhs)
{...}

void swap(Foo &lhs, Foo &rhs)
{
    using std::swap;
    swap(lhs.h, rhs.h);
}

确实,我想知道为什么使用std::swap不会在void swap( Foo &lhs, Foo &rhs)?相反,似乎 std::swap 函数和 void swap(HasPtr &lhs, HasPtr &rhs) 正在重载。

这与以下陈述相反(引自 C++ Primer 5th,第 6.4.1 节):

If we declare a name in an inner scope, that name hides uses of that name declared in an outer scope. Names do not overload across scopes.

让我们考虑以下示例:

#include<iostream>
namespace a{
    void f(int a){  std::cout<< "a::f(int)";}
}
void f(double a){ std::cout<< "f(double)";}

int main(){
  using a::f;
    f(1.11);
}

在这种情况下,当我们使用 using a::f 时,它会将函数 void f(double a) 隐藏在外部作用域中。因此,我们得到如下输出

a::f(int) 

这意味着函数 void f(int a) 在这里被使用,虽然 void f(double a) 会是一个更好的匹配(但它是隐藏的)。

总而言之,似乎 (1)using std::swap 在第一种情况下重载所有在外部范围内的swap函数 (2) using a::f 隐藏第二种情况下所有f函数在外作用域

我的问题是,为什么会有这样的差异?

顺便说一句,这与Function hiding and using-declaration in C++有关,其中所有答案都声称所有交换功能都过载但没有解释原因,所以我在这里打开另一个问题。

最佳答案

当你使用

using a::f;

您正在将 a::f 的声明带到声明区域的范围内。 声明区域部分是这里的关键。

在您的例子中,它是main 的声明区域。 main 中没有其他 f 的声明。因此,f 解析为 a::f

要使 a::f 和全局 f 从 main 可见,请使用:

using a::f;
void f(double a){ std::cout<< "f(double)";}

如果这样做,a::f 和全局 f 都可用于 main

https://ideone.com/ySvGlP 查看它的工作情况.

关于c++ - 为什么使用 std::swap 不会隐藏外部作用域中的其他交换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897588/

相关文章:

javascript - 显示/隐藏 jQuery,显示所有的 div 而不是被点击的

javascript - 根据 View 在自定义谷歌地图上隐藏/显示 KML 图层

JavaScript/Jquery - 隐藏显示的 div,显示另一个,然后重复

c++ - 如何在其他计算机上运行 Qt 5 应用程序 (Windows 7)

c++ - 稀疏矩阵的填充速度非常慢,Eigen 中没有内存增益

f# - 在 F# 中自动打开命名空间

c# - Visual Studio 2010 看不到命名空间,但它存在

c++ - 当进程崩溃时,我如何抑制所有错误对话框(我只希望它静默崩溃)

c++ - 在 Windows 8 XAML 项目中使用 C++/CX 设置边距属性

TypeScript:命名空间与类