编译器是否无法在编译时获取指向派生类的指针并知道它有一个基类?根据以下测试,它似乎不能。有关问题发生的位置,请参阅我最后的评论。
我怎样才能让它工作?
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));
}
};