标签:c templates pointers inheritance template-function
编译器在编译时是否无法获取指向派生类的指针并知道它有一个基类?看来它不能,基于以下测试.请在最后查看我发表问题的评论.
我怎样才能让它发挥作用?
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));
}
};
解决方法:
Derived * derivedD = new Derived;
assert(nonSpecStr == func(derivedD));
这并不像你期望的那样解析为非模板函数,因为这样做必须执行从Derived *到Base *的转换;但是模板版本不需要这种强制转换,这导致后者在重载解析期间更好地匹配.
要强制模板功能与Base和Derived不匹配,您可以使用SFINAE拒绝这两种类型.
#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;
}
输出:
non template function
non template function
non template function
template function
标签:c,templates,pointers,inheritance,template-function 来源: https://codeday.me/bug/20191009/1875933.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。