gpt4 book ai didi

c++ - 为什么ADL找不到函数模板?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:41:39 25 4
gpt4 key购买 nike

C++ 规范的哪一部分限制参数依赖查找在关联的命名空间集中查找函数模板?也就是说,为什么下面main中的最后一个调用编译失败了?

namespace ns {
struct foo {};
template<int i> void frob(foo const&) {}
void non_template(foo const&) {}
}

int main() {
ns::foo f;
non_template(f); // This is fine.
frob<0>(f); // This is not.
}

最佳答案

这部分解释:

C++ 标准 03 14.8.1.6:

[Note: For simple function names, argument dependent lookup (3.4.2) applies even when the function name is not visible within the scope of the call. This is because the call still has the syntactic form of a function call (3.4.1). But when a function template with explicit template arguments is used, the call does not have the correct syntactic form unless there is a function template with that name visible at the point of the call. If no such name is visible, the call is not syntactically well-formed and argument-dependent lookup does not apply. If some such name is visible, argument dependent lookup applies and additional function templates may be found in other namespaces.

namespace A {
struct B { };
template<int X> void f(B);
}
namespace C {
template<class T> void f(T t);
}
void g(A::B b) {
f<3>(b); //ill-formed: not a function call
A::f<3>(b); //well-formed
C::f<3>(b); //ill-formed; argument dependent lookup
// applies only to unqualified names
using C::f;
f<3>(b); //well-formed because C::f is visible; then
// A::f is found by argument dependent lookup
}

关于c++ - 为什么ADL找不到函数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com