【发布时间】:2013-06-25 09:15:46
【问题描述】:
在我最近编写的代码中,我注意到一个奇怪的行为。
当我使用make_pair 并且第一个参数是std::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 and -pedantic-errors)并输出:
2
10
0
为什么会这样?我调查了 cppreference 并没有发现任何暗示这种行为是正确的。我错过了什么吗?
仅供参考,我使用的是 gcc 4.6.3
【问题讨论】:
-
Argument dependent (a.k.a. Koenig) lookup。一些有用的 SO 链接/可能的重复:1、2、3。
-
那很快...谢谢!
-
不客气,问题写得很好,顺便说一句。 ADL 并非没有问题,这是一本好书:What are the pitfalls of ADL?