为什么我的函数不跳过尝试解析为不兼容的模板函数,而是默认解析为常规函数? [复制]

2024-04-25

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 as Derived。重载解析只查看函数的签名,根本不查看函数体。声明一个函数、在某些代码中调用它并稍后定义它会如何工作?

如果您确实想要这种检查类型操作的行为,您可以使用 SFINAE 来实现:

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

这将使替换失败,如果T不支持operator+=.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的函数不跳过尝试解析为不兼容的模板函数,而是默认解析为常规函数? [复制] 的相关文章

随机推荐