资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C++类模板、函数模板全特化以及偏特化的实例用法

这篇文章主要介绍“C++类模板、函数模板全特化以及偏特化的实例用法”,在日常操作中,相信很多人在C++类模板、函数模板全特化以及偏特化的实例用法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++类模板、函数模板全特化以及偏特化的实例用法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

创新互联公司专注于西湖网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供西湖营销型网站建设,西湖网站制作、西湖网页设计、西湖网站官网定制、微信小程序服务,打造西湖网络公司原创品牌,更为您提供西湖网站排名全网营销落地服务。

一、类模板全特化、偏特化

#pragma once#include #include template class TC{public: TC()  { std::cout << "泛化版本构造函数" << std::endl; } void funtest() { std::cout << "泛化版本成员函数" << std::endl; }}; template<>class TC{public: TC() { std::cout << "全特化版本构造函数" << std::endl; } void funtest() { std::cout << "全特化版本成员函数" << std::endl; }}; template<>void TC::funtest(){ std::cout << "全特化版本函数" << std::endl; }

main.cpp

#include #include "template.h"using namespace std; int main(){ TC tchar; tchar.funtest(); TC tint; tint.funtest(); TC tdouble; tdouble.funtest();}

输出:

泛化版本构造函数泛化版本成员函数全特化版本构造函数全特化版本成员函数泛化版本构造函数全特化版本函数

二、类模板偏特化

1、模板参数数量上:

template.h

#pragma once#include #include template class TC2{public: void funtest() { std::cout << "泛化版本成员函数" << std::endl; }}; template class TC2{public: void funtest() { std::cout << "偏特化版本成员函数" << std::endl; }};

main.cpp

#include #include "template.h"using namespace std; int main(){ TC2 tdouble2; tdouble2.funtest(); TC2 tint2; tint2.funtest()}

输出:

泛化版本成员函数偏特化版本成员函数

2、从模板参数范围:

template.h

#pragma once#include #include template class TC3{public: void funtest() { std::cout << "泛化版本成员函数" << std::endl; }}; template class TC3{public: void funtest() { std::cout << "const T偏特化版本成员函数" << std::endl; }}; template class TC3{public: void funtest() { std::cout << "T&偏特化版本成员函数" << std::endl; }}; template class TC3{public: void funtest() { std::cout << "T *偏特化版本成员函数" << std::endl; }};

main.cpp

#include #include "template.h"using namespace std; int main(){ TC3 tint3; tint3.funtest(); TC3 tint3_ref; tint3_ref.funtest(); TC3 tint3_point; tint3_point.funtest(); TC3 tint3_const; tint3_const.funtest();}

输出:

泛化版本成员函数T&偏特化版本成员函数T *偏特化版本成员函数const T偏特化版本成员函数

三、函数模板全特化(不能偏特化)

template.h

#pragma once#include #include template void tfunc(T& a, U& b){ std::cout << "tfunc 泛化版本函数" << std::endl;} template <>void tfunc(int& a, int& b){ std::cout << "tfunc 全特化版本函数" << std::endl;}

main.cpp

#include #include "template.h"using namespace std; int main(){ int a1 = 1; double b1 = 3.2; tfunc(a1, b1); tfunc(a1, a1);}

输出:

tfunc 泛化版本函数tfunc 全特化版本函数

到此,关于“C++类模板、函数模板全特化以及偏特化的实例用法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


当前名称:C++类模板、函数模板全特化以及偏特化的实例用法
文章分享:http://cdkjz.cn/article/pidogh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220