C++_模板函数

参考以下大佬博客:

参考1
参考2
参考3
参考4
参考5

我们为什么需要模板?

   同样的函数,我们要为不同的参数类型写不同的版本,程序的逻辑是一模一样的,只是他们的类型是不一样的。

如下:

void Swap(int & x, int & y)
{
    int tmp = x;
    x = y;
    y = tmp;
}
void Swap (double & xr double & y)
{
    double tmp = x;
    x = y;
    y = tmp;
}

我们可以为上面的两个的函数写一个模板函数,如下:

template<typename T>  // 定义了抽象的数据类型 T
void Swap(T &x,T &y)
{
   T tmp=x;
   x=y;
   y=tmp
}

或者,把关键字typename 替换成 class

template <class T>
void Swap(T & x, T & y)
{
    T tmp = x;
    x = y;
    y = tmp;
}
模板函数被调用时,编译器会根据传入形参的不同,推导T变成对应的数据类型。

在类中写一个方法时,我们同样可以使用模板函数

如下:

class SwapTest{
  public:
	template<typename T>
	void print(const T& t) {
		std::cout << t << std::endl;
	}
}

SwampTest *p = new SwampTest();
p->print("123");

猜你喜欢

转载自blog.csdn.net/longyanbuhui/article/details/84958142