C++ Koenig(参数依赖)查找:如果不同命名空间中的两个命名空间函数具有相同的参数类型怎么办?
C++ Koenig(Argument-Dependent) Lookup: What if two namespaces functions in different namespaces have the same argument types?
如果有
会怎样
Foo::test(Foo::A &a, Bar::B &b, C &c);
和
Bar::test(Foo::A &a, Bar::B &b, C &c);
。
参数的命名空间是否被编译器按顺序考虑(第一个参数优先于参数相关查找),或者这是否被认为是不明确的?
会有歧义。重载集包含两个同样有效的重载:
namespace Bar
{
struct B;
}
namespace Foo
{
struct A{};
void test(A& , Bar::B&, int){}
}
namespace Bar
{
struct B{};
void test(Foo::A& , B&, int){}
}
int main() {
Foo::A a; Bar::B b;
test (a, b, 0);
return 0;
}
在 gcc 上的结果:
prog.cpp: In function 'int main()':
prog.cpp:21:15: error: call of overloaded 'test(Foo::A&, Bar::B&, int)' is ambiguous test (a, b, 0);
^ prog.cpp:10:7: note: candidate: void Foo::test(Foo::A&, Bar::B&, int) void test(A& , Bar::B&, int){}
^ prog.cpp:16:7: note: candidate: void Bar::test(Foo::A&, Bar::B&, int) void test(Foo::A& , B&, int){}
根据标准3.4.2节
For each argument type T in the function call, there is a set of zero or more associated namespaces
因此命名空间 Foo
和 Bar
都将在关联命名空间的集合中。由于函数 test
在两者中都存在,因此会产生歧义。
如果有
会怎样Foo::test(Foo::A &a, Bar::B &b, C &c);
和
Bar::test(Foo::A &a, Bar::B &b, C &c);
。
参数的命名空间是否被编译器按顺序考虑(第一个参数优先于参数相关查找),或者这是否被认为是不明确的?
会有歧义。重载集包含两个同样有效的重载:
namespace Bar
{
struct B;
}
namespace Foo
{
struct A{};
void test(A& , Bar::B&, int){}
}
namespace Bar
{
struct B{};
void test(Foo::A& , B&, int){}
}
int main() {
Foo::A a; Bar::B b;
test (a, b, 0);
return 0;
}
在 gcc 上的结果:
prog.cpp: In function 'int main()':
prog.cpp:21:15: error: call of overloaded 'test(Foo::A&, Bar::B&, int)' is ambiguous test (a, b, 0);
^ prog.cpp:10:7: note: candidate: void Foo::test(Foo::A&, Bar::B&, int) void test(A& , Bar::B&, int){} ^ prog.cpp:16:7: note: candidate: void Bar::test(Foo::A&, Bar::B&, int) void test(Foo::A& , B&, int){}
根据标准3.4.2节
For each argument type T in the function call, there is a set of zero or more associated namespaces
因此命名空间 Foo
和 Bar
都将在关联命名空间的集合中。由于函数 test
在两者中都存在,因此会产生歧义。