1009模板06类模板与函数模板区别

137 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情

1.类模板与函数模板区别主要有两点:

  1. 类模板没有自动类型推导的使用方式

  2. 类模板在模板参数列表中可以有默认参数

2.代码说明:类模板没有自动类型推导的使用方式

2.1错误用法类模板使用时候,不可以用自动类型推导

#include<iostream> 
#include <fstream> 
#include <string>
using namespace std;
//类模板
template<class N, class A>
class H
{
public:
	H(N name, A age)
	{
		this->Name = name;
		this->Age = age;
	}
	void h_idol()
	{
		cout << "name: " << this->Name << " age: " << this->Age << endl;
	}
public:
	N Name;
	A Age;
};

void test()
{
	// 指定NameType 为string类型,AgeType 为 int类型
	H h01("道枝骏佑",19);
	h01.h_idol();
}

int main() {

	test();

	system("pause");

	return 0;
}

image.png

2.2正确的使用方法:必须使用显示指定类型的方式,使用类模板

void test()
{
	// 指定NameType 为string类型,AgeType 为 int类型
	H<string,int> h01("道枝骏佑",19);
	h01.h_idol();
}

3.代码说明:类模板在模板参数列表中可以有默认参数

template<class N, class A = int>
class H
{
public:
	H(N name, A age)
	{
		this->Name = name;
		this->Age = age;
	}
	void h_idol()
	{
		cout << "name: " << this->Name << " age: " << this->Age << endl;
	}
public:
	N Name;
	A Age;
};

void test()
{
	// 指定NameType 为string类型,AgeType 为 int类型
	H<string> h01("道枝骏佑",19);
	h01.h_idol();
}

输出:

name: 道枝骏佑 age: 19

请按任意键继续. . .

template<class N = string, class A = int>
class H
{
public:
	H(N name, A age)
	{
		this->Name = name;
		this->Age = age;
	}
	void h_idol()
	{
		cout << "name: " << this->Name << " age: " << this->Age << endl;
	}
public:
	N Name;
	A Age;
};

void test()
{
	// 指定NameType 为string类型,AgeType 为 int类型
	H< > h01("道枝骏佑",19);
	h01.h_idol();
}

输出:

name: 道枝骏佑 age: 19

请按任意键继续. . .

结论:

  • 类模板使用只能用显示指定类型方式
  • 类模板中的模板参数列表可以有默认参数

类模板的作用

类模板作用

  1. 类模板用于实现类所需数据的类型参数化

  2. 类模板在表示如数据、表、图等数据结构显得特别重要

这些数据结构的表示和算法不受所含的元素类型的影响