Why does the compiler find my function if is not yet declared?

前提是你 提交于 2019-12-03 23:12:00

It works because of two interesting things:

  • two-phase name lookup which is performed to lookup dependent names.
  • and Argument Dependent Lookup (ADL).

Have a look at this:

In short, do_func is a dependent name, so in the first phase (when the file is only parsed but the function template is not instantiated) the compiler does not resolve the name do_func, it only checks the syntax and it sees it is a valid function call. That is all. In the second phase when the function template is instantiated (and thus T is known), the name do_func is resolved and at this time it also uses ADL to lookup the name.

Note that ADL works only for user-defined types. It doesn't work for built-in types, which is why your second code (i.e func(1)) doesn't work!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!