简单了解一下函数模板

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/83313698

泛型编程的基础就是模板的使用。

在编写函数模板的时候有许多需要注意的点。

我们使用一个栗子轻松搞定。

using namespace std;


template<class T, typename U> inline
U func(T & t, U& u);

template<class T, typename U> inline
U func(const T & t,const U& u)
{
	if (u != 0)
	{
		U m = t / u;
		return m;
	}
	else
		return 0;
}

int main()
{
	double D = func(2, 2.0);
	cout << D << endl;
	system("pause");
	return 0;
}

模板的声明和定义需要放在一起,模板的参数需要声明为const。

在编译的时候,遇到函数模板的时候并不会生成代码,只有在实例化模板的时候才会生成代码。

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/83313698
今日推荐