gpt4 book ai didi

c++ - make_pair 命名空间污染

转载 作者:可可西里 更新时间:2023-11-01 17:05:36 25 4
gpt4 key购买 nike

在我最近编写的代码中,我注意到一个奇怪的行为。

当我使用第一个参数为 std::pairmake_pair 时,make_pair 变得“神奇地”在命名空间中可用(我不必使用 std:: 限定符)

#include <iostream>

int main()
{
int i1 = 2; int i2 = 10; int i3 = 0;

// constructing a pair using std::make_pair, everything's okay
std::pair<int,int> key = std::make_pair(i1, i2);

// here, why is make_pair suddenly magically available without the
// std:: namespace qualifier?
// At the same time, using ::make_pair yields and error
// (make_pair has not declared...)
std::pair<std::pair<int,int>, int> mypair = make_pair(key, i3);

std::cout << mypair.first.first << "\n";
std::cout << mypair.first.second << "\n";
std::cout << mypair.second << "\n";

return 0;
}

编译正常(使用 -Wall 和 -pedantic-errors)并输出:

2
10
0

为什么会这样?我查看了 cppreference 并没有发现任何关于此行为正确的提示。我错过了什么吗?

仅供引用,我使用的是 gcc 4.6.3

最佳答案

这是 C++ 的一个鲜为人知的特性,正如 @jrok 所指出的,Koenig Lookup 非常快,或者在现代 C++ 中1)ADL(参数相关查找).它所做的基本上是在参数的 namespace 中搜索要调用的函数(在本例中为 make_pair)。触发 ADL 的参数显然是 std::pair .

1)命名已更改,尽管很多人都知道第一个术语


也许值得一提的是,ADL 对于一种特定类型的函数非常重要:运算符。如果没有 ADL,即使是简单的 C++“你好,世界!”也是不可能的。工作,因为这个:

std::cout << "Hello, world!";

必须这样写:

std::operator<< (std::cout, "Hello, world!");

感谢 ADL,<<正确解析为 std命名空间。


引用资料:

关于c++ - make_pair 命名空间污染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17293445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com