为什么没有命名空间限定符的std :: generate是可访问的?

Nik*_* C. 9 c++ gcc namespaces clang c++11

编译好是正常的吗?

#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> buf;
    generate(buf.begin(), buf.end(), []{ return 0; });
}
Run Code Online (Sandbox Code Playgroud)

(注意std::前面缺少的generate())

这种行为是否记录在某处?或者我偶然发现了编译器或库错误?在我的例子中,在Linux上是GCC 5.3.0和Clang 3.8.0; 两者都使用libstdc ++,所以也许库bug?

Bat*_*eba 3

这是允许的,主要是因为 的参数generate位于std.

代码如下

namespace Foo
{
    struct B{};
    void foo(const B&);
}

int main()
{
    Foo::B b; /*Requires Foo::*/
    foo(b); /*Does not require Foo:: as that is gleaned from the argument*/
}
Run Code Online (Sandbox Code Playgroud)

出于类似的原因是可以接受的。我们称之为参数依赖查找。请参阅https://en.wikipedia.org/wiki/Argument-dependent_name_lookup

  • 不保证参数(向量迭代器)位于“命名空间 std”中。因此这可能无法在某些平台/配置上编译。 (7认同)
  • 当您调用“generate(x, y, f);”时,将在所有参数类型的命名空间中搜索名称“generate”。命名空间是在函数名称搜索开始之前从参数中获取的。 (2认同)