This question already has an answer here:
- Why can't a template function resolve a pointer to a derived class to be a pointer to a base class 1 answer
std::string nonSpecStr = "non specialized func";
std::string const nonTemplateStr = "non template func";
class Base {};
class Derived : public Base {};
template <typename T> std::string func(T * i_obj)
{
( * i_obj) += 1;
return nonSpecStr;
}
std::string func(Base * i_obj) { return nonTemplateStr; }
void run()
{
// Function resolution order
// 1. non-template functions
// 2. specialized template functions
// 3. template functions
Base * base = new Base;
assert(nonTemplateStr == func(base));
Base * derived = new Derived;
assert(nonTemplateStr == func(derived));
Derived * derivedD = new Derived;
// When the template function is commented out, this
// resolves to the regular function. But when the template
// function is uncommented, this fails to compile because
// Derived does not support the increment operator. Since
// it doesn't match the template function, why doesn't it
// default to using the regular function?
assert(nonSpecStr == func(derivedD));
}