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

前端之家收集整理的这篇文章主要介绍了c – Template Explicit Specialization和普通函数有什么区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. template <class T>
  2. void max (T &a,T &b)
  3. {}//generic template #1
  4.  
  5. template<> void max(char &c,char &d)
  6. {} //template specializtion #2
  7.  
  8. void max (char &c,char &d)
  9. {}//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.

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

  1. #include <algorithm>
  2.  
  3. template<typename T>
  4. struct max_implementation
  5. {
  6. T& operator() (T& a,T& b)
  7. {
  8. return std::max(a,b);
  9. }
  10. };
  11.  
  12. template<typename T>
  13. T& max(T& a,T& b)
  14. {
  15. return max_implementation<T>()(a,b);
  16. }

也可以看看:

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

猜你在找的C&C++相关文章