1.2.2 注意事项

96 阅读1分钟
  • 自动推导,必须推导出一致的数据类型
  • 模板必须要确定T的数据类型,才可以使用
#include <iostream>

using namespace std;

template<typename T>
void swap_num(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

template<typename T>
void func()
{
	cout << "Template function" << endl;
}

void test()
{
	int a = 10;
	int b = 20;
	double c = 10;
	// swap_num(a, c);

	// 必须指定一个T
	func<int>();
}

int main()
{
	test();
	system("pause");
	return 0;
}
  • 使用模板必须确定通用数据类型T,并且能够推导出一致的类型