6 模版

本文详细介绍了C++中的模板机制,包括函数模板和类模板的概念、作用、注意事项、用法区别以及常见案例。重点讲解了函数模板的自动类型推导、模板的局限性,以及类模板的成员函数创建时机、继承、类外实现等关键点。
摘要由CSDN通过智能技术生成

1.模板

1.1模板概念

就是提前准备好一些通用、可复用的东西。

C++提供两种模板机制:函数模板和类模板

1.2函数模板

1.2.1函数模板作用:

建立一个通用函数、其函数返回值类型和形参类型可以不具体确定,用一个虚拟的类型进行表示,和java的泛型一样。

语法:

template<typename T>

函数声明或定义

解释:

template  --声明创建模板

typename --表面其后面的符号是一种数据类型,可以用class代替

T  --- 通用的数据类型,名称可以替代,通常为大写字母 

代码示例:

//.h
#pragma once
//函数模板实例

class template_func
{
public:
	template <typename T>
	void temp_func_swap(T &a,T &b);

	void normal_swap(int& a, int& b);

};


template<typename T>
inline void template_func::temp_func_swap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}
//.cpp
#include "template_func.h"

void template_func::normal_swap(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;
}
//.mian
#include "iostream"
using namespace std;
#include "template_func.h"
int main()
{
	int a = 1;
	int b = 2;
	template_func tf = template_func();
	//传统方法若a、b为float或double或其他类型时由于类型不匹配便需要重写一个新的函数
	tf.normal_swap(a, b);
	cout << "a=" << a << "b=" << b << endl;
	//采用函数模板则不需要重写
	//两种方式
	//1-类型自动推导
	tf.temp_func_swap(a, b);
	cout << "a=" << a << "b=" << b << endl;
	//2-显式指定类型
	tf.temp_func_swap<int>(a, b);
	cout << "a=" << a << "b=" << b << endl;
	system("pause");
	return 0;
}

运行结果:

注意:1.函数模板的声明要放在一起,不能一个在.h一个在.cpp中   解决方法参考1.3.7

           2.inline关键字是用于 函数前是表示将该函数直接插入到调用处而不生成函数副本,适用于小函数,优化函数调用,不适用于大函数,不然代码会过于臃肿。

1.2.2函数模板的注意事项

  • 自动类型推导,必须推导出一致的数据类型T,才可以使用

       即不能定义T为int 结果你传给char,这不是荒谬吗!

  • 模板必须要确定出T的数据类型,才可以使用

       即使你的函数模板没有用到T,那也要利用显示指定类型的方法给其一个类型,不然报错!

1.2.3函数模板案例-对不同类型的数组进行排序(int、char)

代码:


//.h代码
#pragma once
//函数模板实例
#include "iostream"
using namespace std;
class template_func
{
public:
	template<typename T>
	void sort(T arr[], int len);
	template<typename T>
	void swap(T& a, T& b);
	template<typename T>
	void print(T arr[],int len);
};
template<typename T>
inline void template_func::temp_func_swap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
inline void template_func::sort(T arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		int index_max = i;
		for (int j = i + 1; j < len; j++)
		{
			if (arr[index_max] > arr[j])
			{
				index_max = j;
			}
		}
		if (index_max != i)
		{
			swap(arr[index_max],arr[i]);
		}
	}
}

template<typename T>
inline void template_func::swap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
inline void template_func::print(T a
  • 25
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DQ小恐龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值