有什么理由 find_if、for_each、count 等不需要 std::?
Is there any reason find_if, for_each, count etc. do not require std::?
我刚刚发现标准 algorithm
header 中的几种算法不需要 std::
。
示例:
#include <vector>
#include <algorithm>
int main() {
std::vector<int> m;
count(m.begin(), m.end(), 0);
count_if(m.begin(), m.end(), [](auto){return true;});
for_each(m.begin(), m.end(), [](auto){});
find_if(m.begin(), m.end(), [](auto){return true;});
}
有什么具体原因吗? g++
和 clang++
都接受上面的代码。
这里发生了两件事。
首先是ADL,或者Argument Dependent Name Lookup。
正在通过 ADL 找到函数。这是因为某些参数(即 vector
的 iterator
类型)位于 std
中,因此当重载解析查找 for_each
时,它会查找通常的命名空间集(在本例中为 root),加上由其参数的命名空间确定的命名空间。
诀窍在于 vector::iterator
不能保证 是 namespace std
中的类型。所以你的代码不能保证工作。它可能是std
中的类型,或者它可能是原始指针,或者它可能是namespace __std__utility_types
中的类型,或者其他任何地方。
所有主要编译器库都有 vector
个非指针迭代器,它们在 namespace std
中,因为替代方案被认为更糟糕。但是缺乏保证意味着您不应该依赖它来获得真正可移植的代码。
我刚刚发现标准 algorithm
header 中的几种算法不需要 std::
。
示例:
#include <vector>
#include <algorithm>
int main() {
std::vector<int> m;
count(m.begin(), m.end(), 0);
count_if(m.begin(), m.end(), [](auto){return true;});
for_each(m.begin(), m.end(), [](auto){});
find_if(m.begin(), m.end(), [](auto){return true;});
}
有什么具体原因吗? g++
和 clang++
都接受上面的代码。
这里发生了两件事。
首先是ADL,或者Argument Dependent Name Lookup。
正在通过 ADL 找到函数。这是因为某些参数(即 vector
的 iterator
类型)位于 std
中,因此当重载解析查找 for_each
时,它会查找通常的命名空间集(在本例中为 root),加上由其参数的命名空间确定的命名空间。
诀窍在于 vector::iterator
不能保证 是 namespace std
中的类型。所以你的代码不能保证工作。它可能是std
中的类型,或者它可能是原始指针,或者它可能是namespace __std__utility_types
中的类型,或者其他任何地方。
所有主要编译器库都有 vector
个非指针迭代器,它们在 namespace std
中,因为替代方案被认为更糟糕。但是缺乏保证意味着您不应该依赖它来获得真正可移植的代码。