为什么我的函数不跳过尝试解析为不兼容的模板函数,并且默认解析为常规函数? [英] Why doesn't my function skip trying to resolve to the incompatible template function, and default to resolving to the regular function?

查看:135
本文介绍了为什么我的函数不跳过尝试解析为不兼容的模板函数,并且默认解析为常规函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


推荐答案

模板参数扣除使您的模板通过将 T 推演为 Derived 来精确匹配。重载分辨率只看函数的签名,而不是看着身体。

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?

如果你实际上想要这种检查类型操作的行为,那么它将如何工作来声明一个函数,在一些代码中调用它,您可以使用SFINAE:

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())
{
  // ...
}

如果 T 不支持 operator $ =

这篇关于为什么我的函数不跳过尝试解析为不兼容的模板函数,并且默认解析为常规函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆