栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 类模板、函数模板全特化、偏特化的使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 全特化版本函数

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/62050.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号