C++模板类具体化

模板类具体化(特化、特例化)有两种:完全具体化和部分具体化。
语法请见示例程序。
具体化程度高的类优先于具体化程度低的类,具体化的类优先于没有具体化的类。
具体化的模板类,成员函数类外实现的代码应该放在源文件中。
示例:

#include <iostream>         // 包含头文件。
using namespace std;        // 指定缺省的命名空间。

// 类模板
template<class T1, class T2>
class AA {                 // 类模板。
public:
	T1 m_x;
	T2 m_y;

	AA(const T1 x, const T2 y) :m_x(x), m_y(y) { cout << "类模板:构造函数。\n"; }
	void show() const;
};

template<class T1, class T2>
void AA<T1, T2>::show() const {    // 成员函数类外实现。
	cout << "类模板:x = " << m_x << ", y = " << m_y << endl;
}
/

// 类模板完全具体化
template<>
class AA<int, string> {
public:
	int      m_x;
	string m_y;

	AA(const int x, const string y) :m_x(x), m_y(y) { cout << "完全具体化:构造函数。\n"; }
	void show() const;
};

void AA<int, string>::show() const {    // 成员函数类外实现。
	cout << "完全具体化:x = " << m_x << ", y = " << m_y << endl;
}
/

// 类模板部分具体化
template<class T1>
class AA<T1, string> {
public:
	T1       m_x;
	string m_y;

	AA(const T1 x, const string y) :m_x(x), m_y(y) { cout << "部分具体化:构造函数。\n"; }
	void show() const;
};

template<class T1>
void AA<T1, string>::show() const {    // 成员函数类外实现。
	cout << "部分具体化:x = " << m_x << ", y = " << m_y << endl;
}
/

int main()
{
	// 具体化程度高的类优先于具体化程度低的类,具体化的类优先于没有具体化的类。
	AA<int, string>    aa1(8, "我是一只傻傻鸟。");   // 将使用完全具体化的类。
	AA<char, string> aa2(8, "我是一只傻傻鸟。");   // 将使用部分具体化的类。
	AA<int, double> aa3(8, 999999);                      // 将使用模板类。
}

推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值