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-05 18:15:37

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+=.

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

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