Is the compiler unable, at compile-time, to take a pointer to a derived class and know that it has a base class? It seems like it can't, based on the following test. See my comment at the end for where the issue occurs.
How can I get this to work?
std::string nonSpecStr = "non specialized func";
std::string const specStr = "specialized func";
std::string const nonTemplateStr = "non template func";
class Base {};
class Derived : public Base {};
class OtherClass {};
template <typename T> std::string func(T * i_obj)
{ return nonSpecStr; }
template <> std::string func<Base>(Base * i_obj)
{ return specStr; }
std::string func(Base * i_obj)
{ return nonTemplateStr; }
class TemplateFunctionResolutionTest
{
public:
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));
OtherClass * otherClass = new OtherClass;
assert(nonSpecStr == func(otherClass));
// Why doesn't this resolve to the non-template function?
Derived * derivedD = new Derived;
assert(nonSpecStr == func(derivedD));
}
};
This doesn't resolve to the non-template function as you expect it to because to do that a cast from
Derived *
toBase *
must be performed; but this cast is not needed for the template version, which results in the latter being a better match during overload resolution.To force the template function to not match both
Base
andDerived
you can use SFINAE to reject both those types.Output: