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

标签 c++ argument-dependent-lookup name-lookup template-function

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/2953684/

相关文章:

c++ - VS2012 上的 decltype 内没有 ADL

c++ - 为什么在其他函数中声明的函数不参与参数相关查找?

c++ - iter_swap 的意义何在?

c++ - 将 'typedef' 从基类传播到 'template' 的派生类

c++ - 带有指向非常量的指针和指向相同地址的常量参数的指针的函数调用

c++ - 如何声明 std::unique_ptr 以及它的用途是什么?

c++ - 参数相关名称查找 : add extra namespace to look into

c++ - 无法显式访问命名空间范围友元

c++ - 使用 swig typemap 将 vector<pair<int,int>> & 从 c++ 方法返回到元组的 python 列表

c++ - 加载 vector 中的所有元素