为什么不能将模板函数解析一个指向派生类是指向一个基类(Why can't a templat

2019-06-26 23:05发布

是编译器不能在编译时,采取一个指向派生类,并知道它有一个基类? 现在看来似乎不可能,基于以下测试。 看到我的评论在年底地方出现问题。

我怎样才能得到这个工作?

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

Answer 1:

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


文章来源: Why can't a template function resolve a pointer to a derived class to be a pointer to a base class