为什么ADL找不到功能模板? [英] Why doesn't ADL find function templates?

查看:88
本文介绍了为什么ADL找不到功能模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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); // 这可以。
frob< 0>(f); // 这不是。
}


解决方案

/ p>

C ++标准03 14.8.1.6


[注意:对于简单函数名,参数相关查找(3.4.2)适用,即使函数名在调用范围内不可见。这是因为调用仍然具有函数调用的语法形式(3.4.1)。但是当使用具有显式模板参数的函数模板时,调用不具有正确的语法形式,除非在调用点处具有可见的函数模板。如果没有这样的名称可见,调用在语法上没有良好的形式,并且参数依赖的查找不适用。如果某些此类名称可见,则参数依赖查找适用,并且可在其他命名空间中找到其他函数模板。




  namespace A {
struct B {};
template< int X> void f(B);
}
命名空间C {
template< class T> void f(T t);
}
void g(A :: B b){
f 3(b); //形式:不是函数调用
A :: f 3(b); // well-formed
C :: f 3(b); //形成错误参数依赖查找
//仅适用于未限定名称
使用C :: f;
f 3(b); //形式良好,因为C :: f是可见的;那么
// A :: f通过参数依赖查找找到
}


What part of the C++ specification restricts argument dependent lookup from finding function templates in the set of associated namespaces? In other words, why does the last call in main below fail to compile?

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.
}

解决方案

This part explains it:

C++ Standard 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
}

这篇关于为什么ADL找不到功能模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆