资讯

精准传达 • 有效沟通

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

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++类模板、函数模板全特化、偏特化的使用
网站URL:http://cdkjz.cn/article/jpecsc.html
多年建站经验

多一份参考,总有益处

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

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

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