是编译器不能在编译时,采取一个指向派生类,并知道它有一个基类? 现在看来似乎不可能,基于以下测试。 看到我的评论在年底地方出现问题。
我怎样才能得到这个工作?
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));
}
};