STL入门——函数模板基本语法

// 01stl_template.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

template <class T>  //语法template <typename T> //告诉编译器,我下面写模板函数
void MySwap(T&a, T &b)
{

	T temp = a;
	a = b;
	b = temp;
}

void test01(){
	int a = 10;
	int b = 20;
	//自动类型推导
	cout<<"a:"<<a<<" b:"<<b<<endl;
	MySwap(a,b);
	
	cout<<"a:"<<a<<" b:"<<b<<endl;

}

void test02(){
	double a = 1.2;
	double b = 3.4;
	//自动类型推导
	cout<<"a:"<<a<<" b:"<<b<<endl;
	MySwap(a,b);
	
	cout<<"a:"<<a<<" b:"<<b<<endl;
	
}

void test03(){
	int a = 10;
	int b = 20;
	
	cout<<"a:"<<a<<" b:"<<b<<endl;
	//显示指定类型
	MySwap<int>(a,b);
	
	cout<<"a:"<<a<<" b:"<<b<<endl;
	
}


int main(int argc, char* argv[])
{
	//test01();
	//test02();
	test03();
	return 0;
}

模板技术,类型参数化,编写代码可以忽略类型

发布了27 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jfztaq/article/details/81607826