Why can't a template function resolve a pointe

2019-02-20 00:17发布

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

1条回答
Juvenile、少年°
2楼-- · 2019-02-20 00:37
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 * to Base * 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 and Derived you can use SFINAE to reject both those types.

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

Output:

non template function
non template function
non template function
template function
查看更多
登录 后发表回答