c++ - 为什么模板函数不能将指向派生类的指针解析为指向基类的指针

标签 c++ templates inheritance pointers template-function

编译器是否无法在编译时获取指向派生类的指针并知道它有一个基类?根据以下测试,似乎不能。请参阅我在末尾的评论以了解问题发生的位置。

我怎样才能让它发挥作用?

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));
    }
};

最佳答案

Derived * derivedD = new Derived;
assert(nonSpecStr == func(derivedD));

这不会像您期望的那样解析为非模板函数,因为要做到这一点,必须执行从 Derived *Base * 的转换;但模板版本不需要此转换,这导致后者在重载解析期间具有更好的匹配性。

要强制模板函数不匹配 BaseDerived,您可以使用 SFINAE 拒绝这两种类型。

#include <string>
#include <iostream>
#include <type_traits>
#include <memory>

class Base {};
class Derived : public Base {};
class OtherClass {};

template <typename T> 
typename std::enable_if<
    !std::is_base_of<Base,T>::value,std::string
  >::type
  func(T *)
{ return "template function"; }

std::string func(Base *)
{ return "non template function"; }

int main()
{
  std::unique_ptr<Base> p1( new Base );
  std::cout << func(p1.get()) << std::endl;

  std::unique_ptr<Derived> p2( new Derived );
  std::cout << func(p2.get()) << std::endl;

  std::unique_ptr<Base> p3( new Derived );
  std::cout << func(p3.get()) << std::endl;

  std::unique_ptr<OtherClass> p4( new OtherClass );
  std::cout << func(p4.get()) << std::endl;
}

输出:

non template function
non template function
non template function
template function

关于c++ - 为什么模板函数不能将指向派生类的指针解析为指向基类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910558/

相关文章:

c++ - 为什么在 C++ 中,类的大小必须始终为用户所知?

c++ - 将工作的 x64 解决方案转换为 x86 (VS2017)

c++ - 如何发布带有模板实现的头文件?

Java:如何创建从继承类获取对象的 getter 方法?

c++ - vector::erase 是否会对 vector 中的元素重新排序?

c++ - 这是使用浮点值进行输入验证的正确方法吗?

javascript - 这是哪个模板lang `<?js`

jquery - 无法使用 jquery 定位使用 Mustache.js 渲染的元素

Java继承和方法重载

PHP:如何调用类层次结构中的所有同名方法?