模板功能中的名称查找规则 [英] name lookup rules in template function

查看:72
本文介绍了模板功能中的名称查找规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

template<typename T>
void adl(T)
{
  cout << "T";
}

struct S
{
};

template<typename T>
void call_adl(T t)
{
  adl(S());
  adl(t);
}

void adl(S)
{
  cout << "S";
}

int main ()
{
  call_adl(S());
}

为什么结果是 TS?模板函数中的名称查找规则是什么?

Why the result is "TS"? What is the name lookup rule inside template function?

http:/ /ideone.com/sB3DnL

推荐答案

模板在定义和定义两个阶段进行编译实例化。第一阶段发生在编译器首先处理模板定义时,并且一些名称立即绑定到定义。在模板实例化之前,有些名称是未绑定的,因为它们取决于模板参数,因此在实例化模板并且知道模板参数之前无法查找它们。

Templates are compiled in two phases, at the point of definition and the point of instantiation. The first phase happens when the template definition is first processed by the compiler, and some names are bound to definitions right away. Some names are left unbound until the template is instantiated, because they depend on template parameters and so cannot be looked up until the template is instantiated and the template arguments are known.

在此调用中:

adl(S());

该函数的模板参数与无关,因此,查找(在第一阶段期间)立即完成,并且它会找到当时唯一的函数 adl

There is nothing that is dependent on the template parameters of the function, so the lookup is done right away (during the first phase) and it finds the only function called adl that is in scope at that point.

在此通话中:

adl(t);

的类型取决于 t ,因此查找被延迟到实例化 t 的实例化为止。当您调用 call_adl(S())时, adl 的第二个重载在范围内,因此当 adl(t)调用执行名称查找,范围内还有另一个函数,它与参数更匹配。

it is dependent on the type of t and so lookup is delayed until instantiation when the type of t is known. When you call call_adl(S()) the second overload of adl is in scope, and so when the adl(t) call performs name lookup there is another function in scope, and it's a better match for the arguments.

这篇关于模板功能中的名称查找规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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