c++ - 3.4.2 从 n3290 草案中查找依赖于参数的名称

标签 c++ c++11 argument-dependent-lookup name-lookup

ISO 草案 n3290 第 3.4.2 节第 1 段中的一点:

When the postfix-expression in a function call is an unqualified-id, other namespaces not considered during the usual unqualified lookup may be searched, and in those namespaces, namespace-scope friend function declarations not otherwise visible may be found. These modifications to the search depend on the types of the arguments (and for template template arguments, the namespace of the template argument).

他们在这里说“这些对搜索的修改取决于参数的类型/模板模板参数/模板参数的命名空间”......任何人都可以用一个例子来解释吗?我尝试使用参数类型..请使用模板参数类型和模板参数类型的命名空间进行解释

最佳答案

考虑一个简单的非限定函数调用:

foo(x);

ADL 表示 foo不仅在封闭范围和调用所在的 namespace 中查找,而且还在 x 类型的 namespace 中查找.例如如果xstd::vector<int>然后命名空间 std也被搜索。因此:

int main() {
    std::vector<int> x,y;
    swap(x,y);
}

没问题,会调用std::swap() .

查找也取决于任何模板参数的命名空间,所以如果 xstd::vector<mynamespace::myclass>然后 mynamespace也包含在查找中。因此

namespace mynamespace {
    struct myclass {};
    void foo(std::vector<mynamespace::myclass> const&){}
}

int main() {
    std::vector<mynamespace::myclass> x;
    foo(x);
}

将调用 mynamespace::foo() .

最后,查找还扩展到用作模板模板参数的任何模板的命名空间。例如

namespace mynamespace {
    template<typename T>
    struct mytemplate
    {};

    template<typename T>
    void bar(T const&) {}
}

template<template<typename> class T>
struct wrapper {};

int main() {
    wrapper<mynamespace::mytemplate> x;
    bar(x);
}

尽管wrapper在全局命名空间中,mynamespace::bar会查到,因为template模板参数用的是xmynamespace::mytemplate .

关于c++ - 3.4.2 从 n3290 草案中查找依赖于参数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6211198/

相关文章:

c++ - native-app 和 chrome-extension 之间的通信

c++ - 如何排序 vector< pair< int , pair<int , pair<string , pair<int , int >>>>>?

c++ - 保留临时 std::string 并返回 c_str() 以防止内存泄漏

c++ - 确定 "generic function"的返回类型

c++ - std::vector<T> 的比较运算符找不到 T 的比较运算符

c++ - ADL的陷阱是什么?

C++: .eof 在一个空文件上

c++ - 以迭代器为参数的模板函数

c++ - grpc c++ 异步完成队列事件

c++ - MPI_Allreduce : very strange false results