加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:35:19 所属栏目:百科 来源:网络整理
导读:template class Tvoid 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之间有什么区别? 解决方法 是一个模板函数 是以前的模板功能的总体专
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读