Overload Resolution with Function Templates

How does overload resolution work when there are both function templates and non-template functions?

When there are both function templates and non-template functions available, the compiler uses a specific set of rules to determine which one to call. Here's how it works:

  1. The compiler first tries to find an exact match with a non-template function. If it finds one, it calls that function.
  2. If there's no exact match with a non-template function, the compiler then tries to find an exact match with a function template. If it finds one, it calls that function.
  3. If there's no exact match with either a non-template function or a function template, the compiler then looks for a non-template function that can be called with implicit conversions.
  4. If there's no non-template function that can be called with implicit conversions, the compiler then looks for a function template that can be called with implicit conversions.

Here's an example:

#include <iostream>

void Print(int x) {
  std::cout << "Non-template function\n";
}

template <typename T>
void Print(T x) {
  std::cout << "Function template\n";
}

int main() {
  Print(10);// calls non-template function
  Print(10.0);// calls function template
}
Non-template function
Function template

In the first call Print(10), the non-template function Print(int) is an exact match, so it's called.

In the second call Print(10.0), there's no exact match with a non-template function. However, the function template Print(T) can be instantiated with T deduced as double to create an exact match, so that's what's called.

Understanding Overload Resolution

Learn how the compiler decides which function to call based on the arguments we provide.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Passing Non-Const References to Overloaded Functions
Why does the compiler prefer a non-const reference parameter over a const reference when I pass a non-const variable?
Overloading Functions with Default Arguments
Can I overload functions that differ only in their default arguments?
Debugging Overload Resolution Failures
How can I debug a situation where the compiler is not selecting the overload I expect it to?
Overloading on const-ness of Parameters
Can I overload a function based on whether a parameter is const or non-const?
Overloading on const-ness of *this
Can I overload member functions based on the const-ness of the object they're called on?
Overloading in Derived Classes
If I overload a function in a base class, can I also overload it in a derived class?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant