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

Why is std::generate accessible without namespace qualifier?

本文关键字:情况下 访问 命名空间 generate std 为什么      更新时间:2023-10-16

这样编译正常吗?

#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> buf;
    generate(buf.begin(), buf.end(), []{ return 0; });
}

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

这种行为有记录吗?或者我偶然发现了编译器或库错误?在我的情况下,它将是Linux上的GCC 5.3.0和Clang 3.8.0;两者都使用libstdc++,所以可能是库错误?

这是允许的,主要是因为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*/
}

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