C++基础 函数模板

函数模板 我比较喜欢叫泛型

为什么要有泛型那  我们看下面代码  俩个函数 除了类型返回值 内容基本一样 如果 业务要求还要多增加string float等   就又出现很多雷同代码 有没有什么办法 给这几个函数 合成一个函数?

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

#include "stdafx.h"
#include <iostream>
#include "stdlib.h"
using namespace std;

int Mess(int a, int b ,int c);
double Mess(double a, double b ,double c);
 

int _tmain(int argc, _TCHAR* argv[])
{
	cout<<" Mess(a,b,c) = " << Mess(2.2,3.3,4.3)<<endl;
 
	
    cout<<" int Mess(a,b) = " << Mess(3,2,12)<<endl;
	system("pause");
	return 0;
}
 
int Mess(int a, int b ,int c)
{
	return a+b+c;
}
double Mess(double a, double b ,double c)
{
	return a+b+c;
}

 

有的  看泛型 函数模板

 template<typename T> 声明类型 

定义带T的方法 T是参数 就是代表了 所有类型 自定义 等等

T Mess(T a, T b ,T c)
{
    return a+b+c;
}

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

#include "stdafx.h"
#include <iostream>
#include "stdlib.h"
using namespace std;

 
 template<typename T>
 T Mess(T a, T b ,T c);


int _tmain(int argc, _TCHAR* argv[])
{

	cout<<" Mess(a,b,c) = " << Mess(2.2,3.3,4.4)<<endl;

    cout<<" int Mess(a,b) = " << Mess(2,3,4)<<endl;
	system("pause");
	return 0;
}
 
 template<typename T>
T Mess(T a, T b ,T c)
{
	return a+b+c;
}
 
发布了279 篇原创文章 · 获赞 43 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/q465162770/article/details/103457910