[英]Argument Dependent Look (ADL) considering template arguments?
I have a couple of namespaces, each with a function template named f
. 我有几个命名空间,每个命名空间都有一个名为f
的函数模板。
// f() and Widget
namespace A {
struct Widget { };
template <typename T>
void func(const T&) { }
}
// f() and caller()
namespace B {
template <typename T>
void func(const T&) { }
template <typename T>
void caller(const T& t) {
func(t); // error occurs here
}
}
template <typename T>
class Wrap { };
int main() {
Wrap<A::Widget> w{};
B::caller(w); // triggers error
}
The above produces the following error 上面产生以下错误
error: call of overloaded ‘func(const Wrap<A::Widget>&)’ is ambiguous
func(t);
~~~~^~~
note: candidate: void B::func(const T&) [with T = Wrap<A::Widget>]
void func(const T&) { }
^~~~
note: candidate: void A::func(const T&) [with T = Wrap<A::Widget>]
void func(const T&) { }
^~~~
Why is A::func
considered if Wrap
is in the global namespace? 如果Wrap
在全局名称空间中,为什么要考虑A::func
? Shouldn't B::caller
call B::func
? B::caller
不应该呼叫B::func
吗?
ADL doesn't just considered the arguments to the function in the case of a template. 在模板的情况下,ADL不仅考虑了函数的参数。 Here you have Wrap<A::Widget>
as the argument to B::caller
. 在这里,您将Wrap<A::Widget>
作为B::caller
的参数。 Because caller
is in namespace B
, B::func
is obviously considered. 因为caller
在namespace B
,所以显然考虑了B::func
。 The reason for A::func
being considered comes from the below (emphasis added) 考虑A::func
的原因来自以下(添加了重点)
N659 6.4.2/(2.2) [basic.lookup.argdep] N659 6.4.2 /(2.2)[basic.lookup.argdep]
If T is a class type (including unions), its associated classes are: the class itself; 如果T是一个类类型(包括并集),则其关联的类为:类本身; the class of which it is a member, if any; 它所属的类(如果有); and its direct and indirect base classes. 及其直接和间接基类。 Its associated namespaces are the innermost enclosing namespaces of its associated classes. 其关联的名称空间是其关联类的最内部封闭的名称空间。 Furthermore, if T is a class template specialization, its associated namespaces and classes also include: the namespaces and classes associated with the types of the template arguments provided for template type parameters [...] 此外,如果T是类模板专业化,则其关联的名称空间和类还包括:与为模板类型参数提供的模板参数类型相关的名称空间和类 [...]
Because A::Widget
is a template argument to Wrap
, A
is also an associated namespace of Wrap<A::Widget>
因为A::Widget
是Wrap
的模板参数,所以A
也是Wrap<A::Widget>
的关联命名空间
This example can be made to compile as expected by preventing ADL by using the qualified name: 通过使用限定名称来防止ADL,可以使此示例按预期进行编译:
template <typename T>
void caller(const T& t) {
B::func(t);
}
or by enclosing the function name in paretheses 或将函数名称括在parethese中
template <typename T>
void caller(const T& t) {
(func)(t);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.