模板

本文详细介绍了C++中的泛型编程,包括函数模板的使用,如何实现多参数模板以及类模板中动态数组的实现。通过示例展示了如何利用模板实现代码复用,提高程序的灵活性。同时讨论了模板声明与实现的位置对链接错误的影响,建议将模板声明和实现放在同一个头文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

函数模板

多参数模板

类模板之动态数组


 泛型,是一种将类型参数化以达到代码复用的技术,C++中使用模板来实现泛型
模板的使用格式如下
template <typename\class T>
typename和class是等价的

模板没有被使用时,是不会被实例化出来的
模板的声明和实现如果分离到.h和.cpp中,会导致链接错误
一般将模板的声明和实现统一放到一个.hpp文件中

函数模板

template <typename T>
void swapValues(T& v1, T& v2){
    T temp = v1;
    v1 = v2;
    v2 = temp;
}

int main(){
    int a = 10;
    int b = 20;
    swapValues<int>(a,b);
}

多参数模板

template <class T1, class T2>
void display(const T1 &v1, const T2 &v2){
    cout << v1 << endl;
    cout << v2 << endl;
}

display(20, 1.7);

类模板之动态数组

#pragma once
#include <iostream>
using namespace std;

template <typename Item>
class Array {
    // 重载的<<运算符  友元函数支持泛型要加上<>
	friend ostream &operator<<<>(ostream &, const Array<Item> &);
	// 用于指向首元素
	Item *m_data;
	// 元素个数
	int m_size;
	// 容量
	int m_capacity;
	void checkIndex(int index);
public:
	Array(int capacity = 0);
	~Array();
	void add(Item value);
	void remove(int index);
	void insert(int index, Item value);
	Item get(int index);
	int size();
	Item operator[](int index);
};

template <typename Item>
Array<Item>::Array(int capacity) {
	m_capacity = (capacity > 0) ? capacity : 10;

	// 申请堆空间
	m_data = new Item[m_capacity];
}

template <typename Item>
Array<Item>::~Array() {
	if (m_data == NULL) return;
	delete[] m_data;
}

template <typename Item>
void Array<Item>::checkIndex(int index) {
	if (index < 0 || index >= m_size) {
		// 报错:抛异常
		throw "数组下标越界";
	}
}

template <typename Item>
void Array<Item>::add(Item value) {
	if (m_size == m_capacity) {
		// 扩容
		/*
		1.申请一块更大的新空间
		2.将旧空间的数据拷贝到新空间
		3.释放旧空间
		*/
		cout << "空间不够" << endl;
		return;
	}

	m_data[m_size++] = value;
}

template <typename Item>
void Array<Item>::remove(int index) {
	checkIndex(index);

}

template <typename Item>
void Array<Item>::insert(int index, Item value) {
	
}

template <typename Item>
Item Array<Item>::get(int index) {
	checkIndex(index);

	return m_data[index];
}

template <typename Item>
int Array<Item>::size() {
	return m_size;
}

template <typename Item>
Item Array<Item>::operator[](int index) {
	return get(index);
}

template <typename Item>
ostream &operator<<<>(ostream &cout, const Array<Item> &array) {
	cout << "[";

	for (int i = 0; i < array.m_size; i++) {
		if (i != 0) {
			cout << ", ";
		}
		cout << array.m_data[i];
	}

	return cout << "]";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值