c ++ function pointer exchange and the exchange template reference template class

Function template

Template technology, parameterized types, type writing code can be ignored
in order to allow the compiler to distinguish between an ordinary function or function template

// 模板.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
template<typename T>//template<class t>
//告诉编译器,下边是模板函数
void Myswap(T*a, T*b)
{
	T temp= *a;
	*a = *b;
	*b = temp;
	//cout << "in a=" << *a << "  b=" << *b << endl;
}
template<typename T>
void Myswap1(T&a, T&b)
{
	T temp = a;
	a = b;
	b = temp;
}
void test()
{
	int a = 10, b = 20;
	double c = 3.0, d = 4.0;
	cout << "a=" << a << "  b=" << b << endl;
	//1.自动类型推导
	Myswap(&a, &b);
	cout << "a=" << a << "  b=" << b << endl;
	cout << "c=" << c << "  d=" << d<< endl;
	//1.自动类型推导,编译器根根据传的值自动推导类型
	Myswap1(c, d);
	cout << "c=" << c << "  d=" << d << endl;
	//2显示指定类型
	Myswap1<int>(a,b);//不能传 c,d
}
int main()
{
	test();
    return 0;
}


**** function template does not allow automatic type conversion, common templates can be automated type conversion
function templates can be overloaded
compiler priority to the ordinary function, if the template can produce better good match, then select a template, if you have to call the template , then to
myAdd <> (a, b) // angle brackets


Class Template

// 模板.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
template<typename T>
class Person {
public:
	Person(T id, T age)
	{
		cout << "hhh" << endl;
		this->id = id;
		this->age = age;
	}
	void show()
	{
		cout << "id " << id << "age" << age << endl;
	}
private:
	T id;
	T age;
};
void test01()
{
	//函数模板在调用时可以自动类型推导
	//类模板必须显示指定类型
	Person<int> p(10, 20);
	p.show();
}

int main()
{
	test01();
    return 0;
}


Int type to char type and sort the array

// 模板.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
template<class T>
void print(T *arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}
template<typename T>
void mysort(T *arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		for (int j = i + 1; j < len; j++)
		{
			//从大到小排序
			if (arr[i] < arr[j])
			{
				T temp;
				temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
			}
		}
	}
}
int main()
{
	int arr[] = { 1,5,4,2,3,9,6,8 };
	int len = sizeof(arr)/sizeof(int);//总长度/单位长度=个数
	print(arr, len);
	mysort(arr, len);
	print(arr, len);
	char ch[] = { 'a','h','b','p' };
	int len1 = sizeof(ch) / sizeof(char);
	print(ch, len1);
	mysort(ch, len1);
	print(ch, len1);
	return 0;
}


Published 26 original articles · won praise 2 · Views 2159

Guess you like

Origin blog.csdn.net/weixin_41375103/article/details/104551446