jeudi 23 avril 2015

c++ function resolution selects templated version over plain 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 surprising, because I thought that the plain function will be selected over any templated version. Why does this happen?

Another thing I noticed while playing around is that: if I put the normal function void f(double) before the templated void entry(T) function the code will call the normal function, basically outputting:

normal f(double)

Therefore my other question: why does the order matter in this particular example?

Aucun commentaire:

Enregistrer un commentaire