Search code examples
c++templatesoverload-resolution

Template function without explicit usage of type, strange overload ranking


I couldn't come up with a better title for my question. Basically it resumes to the following code:

#include <iostream>

template<typename T> // generic
void f(T)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

template<typename T> 
void f(int)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main()
{   
    f(42);        // calls generic f(T)
    f<int>(42);   // calls f(int)
    f<int>(42.2); // also calls f(int)
}

Live on Coliru

My question(s):

  1. Is the second overload syntactically OK? The type is not used anywhere in it. It seems to be OK, as the program compiles with both g++ and clang++.
  2. How does the compiler choose which overload to call? I understand maybe why f(42) calls the generic f(T), however why does f<int>(42) and f<int>(42.2) result in the second overload being called?

Solution

    1. Yes. It's just that T can't be deduced from the argument. That's ok because you've supplied a template argument in (2) and (3).

    2. It will choose the deduced version (1) if you don't specify T when you call it (example 1). If you specify T at the call site it won't try to deduce T because you already told it what T was (example 2 and 3).