[C++] function template

  • Another C ++ programming ideas called generic programming  techniques, the main advantage is the template

  • C++ provides two template mechanisms: function templates and class templates

1 Function template syntax

Function template function:

Establish a general function, the function return value type and formal parameter type can not be specified specifically, represented by a virtual type .

grammar:

template<typename T>
函数声明或定义

Explanation:

template --- Declare to create a template

typename --- The symbol behind it is a data type, which can be replaced by class

T --- General data type, the name can be replaced, usually in uppercase letters

#include <iostream>
using namespace std;

//利用模版提供通用的交换函数
template<typename T>
void mySwap(T& a, T&b)
{
	T temp = a;
	a = b;
	b = temp;
}

void test01()
{
	int a = 10;
	int b = 20;
	//利用模板实现交换
	//1、自动类型推导
	mySwap(a, b);

	//2、显示指定类型
	mySwap<int>(a, b);

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
}

int main(void)
{
	test01();

	system("pause");
	return 0;
}

to sum up:

  • The function template uses the keyword template;

  • There are two ways to use function templates: automatic type inference and display of specified types;

  • The purpose of the template is to improve the reusability and parameterize the type.

2 Notes on function templates

Precautions:

  • Automatic type derivation, you must derive a consistent data type T before you can use it

  • The template must determine the data type of T before it can be used

#include <iostream>
using namespace std;

//1 自动类型推导,必须推导出一致的数据类型T,才可以使用
template <typename T>
void mySwap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

void test02()
{
	int a = 10;
	int b = 20;
	char c = 'a';

	mySwap(a, b);
	//mySwap(a, c);   //错误,推导不出一致的T类型

}

// 2、模板必须要确定出T的数据类型,才可以使用
template <typename T>
void func()
{
	cout << "func的调用" << endl;
}

void test002()
{
	//func();          //错误,模板不能独立使用,必须确定出T的类型
	func<int>();       //利用显示指定类型的方式,给T一个类型,才可以使用该模板
}

int main(void)
{
	test02();
	test002();

	system("pause");
	return 0;
}

to sum up:

  • When using a template, a common data type T must be determined, and a consistent type must be deduced

3 The difference between ordinary functions and function templates

The difference between ordinary functions and function templates:

  • Automatic type conversion (implicit type conversion) can occur when ordinary function calls

  • When the function template is called, if automatic type inference is used, implicit type conversion will not occur

  • If you use the display of the specified type, implicit type conversion can occur

#include <iostream>
using namespace std;

//普通函数和函数模版的区别
//1、普通函数调用可以发生隐式类型转换
//2、函数模版 用自动类型推导,不可以发生隐式类型转换
//3、函数模版 用显示指定类型,可以发生隐式类型转换

//普通函数
int myAdd04(int a, int b)
{
	return a + b;
}

//函数模版
template<typename T>
T myAdd004(T a, T b)
{
	return a + b;
}


void test04()
{
	int a = 10;
	int b = 20;
	char c = 'a';    //'a' - 97

	//正常调用
	cout << myAdd04(a, b) << endl;
	//隐式转换
	cout << myAdd04(a, c) << endl;

	//函数模版
	cout << myAdd004(a, b) << endl;          //正确
	//cout << myAdd004(a, c) << endl;        //报错,使用自动类型推导时,不会发生隐式类型转换
	cout << myAdd004<int>(a, c) << endl;     //正确,如果用显示指定类型,可以发生隐式类型转换
}


int main4(void)
{
	test04();
	system("pause");
	return 0;
}

Summary: It is recommended to use the method of displaying the specified type and calling the function template, because you can determine the general type T by yourself

4 Calling rules of ordinary functions and function templates

The calling rules are as follows:

  1. If both the function template and the ordinary function can be implemented, the ordinary function is called first

  2. You can force a function template to be called through an empty template parameter list

  3. Function templates can also be overloaded

  4. If the function template can produce a better match, call the function template first

#include <iostream>
using namespace std;

//普通函数与函数模板的调用规则
//1. 如果函数模板和普通函数都可以实现,优先调用普通函数
//2. 可以通过空模板参数列表来强制调用函数模板
//3. 函数模板也可以发生重载
//4. 如果函数模板可以产生更好的匹配, 优先调用函数模板


void myPrint(int a,int b)
{
	cout << "调用的是普通函数" << endl;
}

template <typename T>
void myPrint(T a, T b)
{
	cout << "调用的是函数模版" << endl;
}

//3. 函数模板也可以发生重载
template <typename T>
void myPrint(T a, T b,T c)
{
	cout << "调用的是重载函数模版" << endl;
}

void test05()
{
	int a = 10;
	int b = 20;
	myPrint(a, b);        //优先普通函数  【如果普通函数只有声明,会报错】
	

	//通过空模版参数列表,强制调用函数模版
	myPrint<>(a, b);     //函数模版

	myPrint(a, b, 100);

	//4. 如果函数模板可以产生更好的匹配, 优先调用函数模板
	char c1 = 'a';
	char c2 = 'b';
	myPrint(c1, c2);    //调用普通的需要转换,所以是调用模版
}

int main(void)
{
	test05();

	system("pause");
	return 0;
}

Summary: Since function templates are provided, it is best not to provide ordinary functions, otherwise ambiguity is likely to occur

5 Limitations of templates

limitation:

  • The versatility of templates is not a panacea

E.g:

	template<class T>
	void f(T a, T b)
	{ 
    	a = b;
    }

The assignment operation provided in the above code, if the incoming a and b are an array, it cannot be implemented

Another example:

template<class T>
void f(T a, T b)
{ 
    if(a > b) { ... }
}

In the above code, if the data type of T is passed in a custom data type like Person, it will not work properly.

 

Therefore, in order to solve this problem, C++ provides template overloading, which can provide specific templates for these specific types .

#include <iostream>
#include <string>
using namespace std;

//自定义数据类型
class Person
{
public:
	Person(string name,int age):m_Name(name),m_Age(age)
	{

	}
	string m_Name;
	int m_Age;
};


//对比两个数据是否相等
template <class T>
bool myCompare(T& a, T& b)
{
	if (a == b)
	{
		return true;
	}
	return false;
}

void test06()
{
	int a = 10;
	int b = 10;
	bool ret = myCompare(a, b);

	if (ret)
	{
		cout <<"a == b" << endl;
	}
	else
	{
		cout << "a != b" << endl;
	}
	
}


//利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCompare(Person& p1, Person& p2)
{
	if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age)
	{
		return true;
	}
	return false;
}


//自定义数据类型的比较
void test006()
{
	Person p1("Tom", 10);
	Person p2("Tom", 10);
	bool ret = myCompare(p1, p2);

	if (ret)
	{
		cout << "p1 == p2" << endl;
	}
	else
	{
		cout << "p1 != p2" << endl;
	}
}

int main(void)
{
	test06();

	test006();

	system("pause");
	return 0;
}

to sum up:

  • The use of specific templates can solve the generalization of custom types

  • Learning templates is not to write templates, but to use the templates provided by the system in STL

Guess you like

Origin blog.csdn.net/Zhouzi_heng/article/details/114703371