Template code will not compile (delayed search)

I have two strange cases where it seems that the code should compile, but it is not. To get started, consider the code below that compiles successfully:

struct A { template <class T> void member_func(T t) { global_func(t); } }; int main() { } 

But if I fully qualify global_func by prefixing with "::", it does not compile with the error "global_func" has not been declared in this area ":

 struct A { template <class T> void member_func(T t) { ::global_func(t); } }; int main() { } 

Also, if I try to pass global_func to boost :: bind, it does not compile (same error):

 #include <boost/bind.hpp> class A { template <class T> void member_func(T t) { boost::bind(global_func)(t); } }; int main() { } 

Why doesn't it compile in these cases? It seems that the member_func () template method is not created, so it should not detect the missing function error.

+4
source share
1 answer

In the first example, global_func is a dependent name because it is the unqualified name used in the postfix () expression, where the expression in parentheses depends on the template parameter. This means that the search should be delayed until the moment the template is created, when the template parameter is known, and ADL can have an effect.

In the second example ::global_func is a qualified name, so its search is not delayed and you need to search for it on the pointer where the template is defined.

Similarly, in the expression boost::bind(global_func) , global_func not used in the expression, which depends on the template parameter, so repeated searches are not delayed, and the declaration should be visible at the definition point of the member template.

+10
source

Source: https://habr.com/ru/post/1382174/


All Articles