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:
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.
Answers to questions are automatically generated and may not have been reviewed.
Learn how the compiler decides which function to call based on the arguments we provide.