3.4.2 Argument-dependent name lookup from n3290 Draft

霸气de小男生 提交于 2019-12-22 04:08:49

问题


A point from ISO draft n3290 section 3.4.2 paragraph 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).

Here they said aboout "these modifications to the search depend on the types of the arguments / template template arguments / namespace of the template argument " ...Can any one expalin with an example please? I tried with argumetn types..please expalin with template template argument types & namespace of the template argument type


回答1:


Consider a simple unqualified function call:

foo(x);

ADL means that foo is looked up not just in the enclosing scope, and the namespace that the call is in, but also the namespace of the type of x. e.g. if x is a std::vector<int> then namespace std is also searched. Thus:

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

is OK, and will call std::swap().

The lookup also depends on the namespace of any template arguments too, so if x is std::vector<mynamespace::myclass> then mynamespace is also included in the lookup. Thus

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

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

will call mynamespace::foo().

Finally, the lookup also extends to the namespaces of any templates used as template template parameters. e.g.

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);
}

Even though wrapper is in the global namespace, mynamespace::bar will be found, because the template template parameter used for x is mynamespace::mytemplate.



来源:https://stackoverflow.com/questions/6211198/3-4-2-argument-dependent-name-lookup-from-n3290-draft

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!