C++自学33:函数模板

和java的方法级泛型很像

//template和typename是关键字
//T是自己随便写的,写什么都可以
template <typename T> T add(T t1, T t2) {
    
    
	return t1 + t2;
}

int main()
{
    
    
	int a = add(1,2);
	float b = add(3.14f, 3.14f);
	std::cout << a << std::endl;
	std::cout << b << std::endl;
}

比较简单,需要注意的是函数参数是指针或者引用的情况,本文中就不演示了,因为类似这种情况随用随试就可以,也没必要背下来,用的次数多了自然而然也就记住了

猜你喜欢

转载自blog.csdn.net/u011624903/article/details/111054854
今日推荐