#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());
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With