简体   繁体   English

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

[英]what is the difference between Template Explicit Specialization and ordinary function?

template <class T>
void max (T &a ,T &b)
{}//generic template   #1

template<> void max(char &c, char &d)
{} //template specializtion    #2

void max (char &c, char &d)
{}//ordinary function      #3

what is difference between 1 ,2, and 3? 1,2和3有什么区别?

  1. is a template function 是一个模板功能
  2. is a total specialization of the previous template function (doesn't overload!) 是前一个模板函数的完全特化(不过载!)
  3. is an overload of the function 是函数的重载

Here is an excerpt from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices : 以下是C ++编码标准的摘录:101规则,指南和最佳实践

66) Don't specialize function templates 66)不要专门化功能模板

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. 毕竟,如果你编写了一个具有相同签名而不是函数模板特化的nontemplate函数,那么将始终选择nontemplate函数,因为它总是被认为是比模板更好的匹配。

The book advises you to add a level of indirection by implementing the function template in terms of a class 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);
}

See also: 也可以看看:

The matching rules for template parameters subtly differ from that of overloaded functions. 模板参数的匹配规则与重载函数的匹配规则略有不同。 An example of what differs can be seen when you try to invoke max() with arguments of different tyoes: 当您尝试使用不同tyoes的参数调用max()时,可以看到不同的示例:

max(1,'2');

This will match the overloaded function, but neither the base template nor the specialization. 这将匹配重载函数,但既不匹配基本模板也不匹配特化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM