示例:求最大项

  1. #include<iostream>
  2. using namespace std;
  3. template <class T>
  4. void Max(T a,T b)
  5. {
  6. if(a>b)
  7. cout<<a<<" is greater"<<endl;
  8. else
  9. cout<<b<<" is greater"<<endl;
  10. }
  11. int main() {
  12. string a="abc";
  13. string b="xyz";
  14. Max(a, b);
  15. Max<double>(1.1, 2.1);
  16. }

传递参数

必须显式调用,参数可以缺省

  1. #include<iostream>
  2. using namespace std;
  3. T* newmemomry() {
  4. T *p = new T[size];
  5. cout << "memory has been malloc" << endl;
  6. return p;
  7. }
  8. void testnewmemomry() {
  9. int *p = newmemomry<int, 10>();
  10. double *q = newmemomry<double, 10>();
  11. char *r = newmemomry<char, 10>();
  12. }
  13. int main() {
  14. testprint();
  15. }

函数模板重载

先匹配普通函数
再寻求函数模板

  1. #include<iostream>
  2. using namespace std;
  3. template<class T>
  4. void print(T a)
  5. {
  6. cout << "函数模板..." << endl;
  7. cout<<a<<endl;
  8. }
  9. void print(int a)
  10. {
  11. cout << "普通函数..." << endl;
  12. cout<<a<<endl;
  13. }
  14. void testprint() {
  15. print(1);
  16. print(1.1);
  17. print<int>(1);
  18. print("hello");
  19. }
  20. int main() {
  21. testprint();
  22. }