Why doesn't my function skip trying to resolve to the incompatible template function, and default to resolving to the regular function? [duplicate]

泄露秘密 提交于 2019-12-07 10:40:38

问题


std::string nonSpecStr = "non specialized func";
std::string const nonTemplateStr = "non template func";

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

template <typename T> std::string func(T * i_obj)
{ 
   ( * i_obj) += 1;
   return nonSpecStr; 
}

std::string func(Base * i_obj) { return nonTemplateStr; }

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

   Derived * derivedD = new Derived;

   // When the template function is commented out, this
   // resolves to the regular function. But when the template
   // function is uncommented, this fails to compile because
   // Derived does not support the increment operator. Since
   // it doesn't match the template function, why doesn't it
   // default to using the regular function?
   assert(nonSpecStr == func(derivedD));
}

回答1:


Template argument deduction makes your template function an exact match with by deducing T as Derived. Overload resolution only looks at the signature of the function, and doesn't look at the body at all. How else would it work to declare a function, call it in some code, and define it later?

If you actually want this behaviour of checking the operations on a type, you can do so with SFINAE:

// C++11
template<class T>
auto f(T* p)
    -> decltype((*p)+=1, void())
{
  // ...
}

This will make substitution fail if T doesn't support operator+=.




回答2:


Type T can be an exact match which will not require an implicit conversion in the first place, so it is preferable to your Base class version of the non-template function.

You can specialize the template function for a type that doesn't meet the implicit contract and have it call the non templated function instead if you find this problematic. Equally, you can provide non-templated versions matching the exact derived classes you will use so that implicit conversions are not required. Both of these options are more painful than just not using that operator though. Code your templates so their implicit template contracts require as little as possible :)



来源:https://stackoverflow.com/questions/11938359/why-doesnt-my-function-skip-trying-to-resolve-to-the-incompatible-template-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!