你问:
上面的示例是否简单地表示,如果我以第一个参数作为任何类的对象调用任何函数,并且如果该函数在当前名称空间中找不到,则编译器会在第一个对象的名称空间中找到所需的函数?
回答:
通过使用ADL,编译器将找到所有可能的函数。它恰好找到一个,它将使用它。如果发现多个,则会出错。仅当无法在当前名称空间中找到函数时,它才会使用ADL。
范例1:
#include <iostream>
using namespace std;
namespace NS1
{
struct A {};
int foo(A a) { return 10; }
}
namespace NS2
{
struct A {};
int foo(A a) { return 20; }
}
int main()
{
cout << foo(NS1::A()) << endl; // Resolves to NS1::foo by using ADL
cout << foo(NS2::A()) << endl; // Resolves to NS2::foo by using ADL
}
范例2:
#include <iostream>
using namespace std;
namespace NS1
{
struct A {};
}
int foo(NS1::A a) { return 10; }
namespace NS2
{
struct A {};
int foo(A a) { return 20; }
}
int foo(NS2::A a) { return 30; }
int main()
{
cout << foo(NS1::A()) << endl; // Resolves to ::foo(NS1::A)
cout << foo(NS2::A()) << endl; // Unable to resolve.
// ::foo(NS2::A) and NS2::foo(NS2::A) are
// equally valid candidates.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句