When overloading a templated function, how should the compiler chose which version of the function to call if it has the option to either:
- Call a templated version of the function (such as
func<T>(foo)
). - Call an overloaded version of the function which is not itself templated but where the type of the parameter being passed to the function inherits from the type specified in the overloaded function template.
Consider the following C++ code:
#include <stdio.h>
struct Parent {};
struct Child : public Parent {};
template <typename T>
void func(T) {
printf("func(T)\n");
}
void func(Parent) {
printf("func(Parent)\n");
}
int main() {
func(1);
func(Parent());
func(Child());
}
Compiled with gcc or clang, this outputs:
func(T)
func(Parent)
func(T)
The first two lines are expected and make sense. However, in the call func(Child())
, it could just as easily call func(Parent)
(which seems like, if anything, what it should do).
As such, I have two main questions:
- What are the exact rules laid out by the standard as to how to resolve such conflicts? There is some information in this question/answer, but if anything it conflicts with what I am observing.
- Is there any way to force the compiler to call
func(Parent)
when passed aChild
?
I can get around this requirement in my own code and this example is a simplified version of what I am trying to do, but I believe that it is the same problem.