Johnny
Johnny

Reputation: 447

What are the priorities when calling template and non template functions?

Why does this:

#include <iostream>
using namespace std;

template <class T> void f(T t) {cout << "A";}
template <> void f(float x) {cout << "B";}
void f(float x) {cout << "C";}

int main()
{
    float x;
    f(x);
    f<>(x);
    f<float>(x);

    return 0;
}


display this: CBB ?

It's very unclear for me especially why f<float>(x); displays B. Could you tell me some more general rules about the priority of calling template and non template functions with the same name ?

Upvotes: 3

Views: 322

Answers (1)

Casey
Casey

Reputation: 10946

As Walter E Brown teaches in his 2018 CppCon talk there are levels of priority for templates based on specialization:

  • non-template overloads are always picked first; non-templates are more specialized than templates themselves.
  • specialized templates (your template <> void f(float)); the way I remember it is these types of templates "specify" their template arguments.
  • generic templates (i.e. less specialized) are picked last.

Upvotes: 3

Related Questions