C ++ function resolution selects the template version by a simple function

Consider the following code:

#include <iostream> template<typename T> void f(T t) { (void)t; std::cout << "templated f(T)\n"; } template<typename T> void entry(T t) { f(t); } void f(double d) { (void)d; std::cout << "normal f(double)\n"; } int main() { double d = 0.0; entry(d); return 0; } 

Output:

templated f (T)

I find this amazing because I thought that a simple function would be chosen by any template version. Why is this happening?

Another thing that I noticed during the game is that: if I put the normal function void f(double) before using templated void entry(T) , the code will call a normal function, basically outputting:

normal f (double)

So my other question is: why the question of order in this particular example?

+6
source share
2 answers

f is a dependent name because it depends on t , whose type is a template parameter. The rules for finding names for dependent names are given in [temp.dep.res] / 1:

When resolving dependent names, names from the following sources are taken into account:

  • Ads that are visible at the template definition point.
  • Declarations from namespaces associated with function argument types both from context context (14.6.4.1) and definition context.

In other words, usually searching by name inside a template only finds the names that were declared before the template definition (which is not surprising, since it is the same as for non-templates). The second marker point allows you to declare names after defining a pattern, but only when ADL occurs. This is not so if the argument is a fundamental type, for example double .

+7
source

The overload for f(double) not displayed to the compiler when parsing the entry(T) pattern. Therefore, it will not participate in overload resolution when creating an entry(T) instance. This is just an obscure rule when it comes to resolving overloads in the context of instantiating a template. To consider congestion, it must already be visible in the translation unit before the template definition has been analyzed.

0
source

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


All Articles