c – Template Explicit Specialization和普通函数有什么区别?

c – Template Explicit Specialization和普通函数有什么区别?,第1张

概述template <class T>void max (T &a ,T &b){}//generic template #1template<> void max(char &c, char &d){} //template specializtion #2void max (char &c, char &d){}//ordinary function #3 1
template <class T>voID max (T &a,T &b){}//generic template   #1template<> voID max(char &c,char &d){} //template specializtion    #2voID max (char &c,char &d){}//ordinary function      #3

1,2和3之间有什么区别?

解决方法 >是一个模板函数
>是以前的模板功能的总体专业化(不会超载!)
>是功能的重载

这是C++ Coding Standards: 101 Rules,Guidelines,and Best Practices摘录:

66) Don’t specialize function templates

Function template specializations never participate in overloading: Therefore,any specializations you write will not affect which template gets used,and this runs counter to what most people would intuitively expect. After all,if you had written a nontemplate function with the IDentical signature instead of a function template specialization,the nontemplate function would always be selected because it’s always consIDered to be a better match than a template.

本书建议您通过根据类模板实现功能模板来添加间接级别:

#include <algorithm>template<typename T>struct max_implementation{  T& operator() (T& a,T& b)  {    return std::max(a,b);  }};template<typename T>T& max(T& a,T& b){  return max_implementation<T>()(a,b);}

也可以看看:

> Why Not Specialize Function Templates?
> Template Specialization and Overloading

总结

以上是内存溢出为你收集整理的c – Template Explicit Specialization和普通函数有什么区别?全部内容,希望文章能够帮你解决c – Template Explicit Specialization和普通函数有什么区别?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248314.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存