name lookup rules in template function

后端 未结 1 1978
轮回少年
轮回少年 2020-12-30 07:28
#include 
using namespace std;

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

struct S
{
};

template
void cal         


        
相关标签:
1条回答
  • 2020-12-30 08:27

    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.

    In this call:

    adl(S());
    

    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.

    In this call:

    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.

    0 讨论(0)
提交回复
热议问题