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

前端之家收集整理的这篇文章主要介绍了c – Template Explicit Specialization和普通函数有什么区别?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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

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&C++相关文章