C++ Template应用详解

2020-01-06 16:35:07于海丽


//method.h
template<class T> void swap(T& t1, T& t2);

#include "method.cpp"

#include <vector>
using namespace std;
template<class T> void swap(T& t1, T& t2) {
  T tmpT;
  tmpT = t1;
  t1 = t2;
  t2 = tmpT;
}

template<> void swap(std::vector<int>& t1, std::vector<int>& t2) {
  t1.swap(t2);
}

template<>前缀表示这是一个专门化,描述时不用模板参数,使用示例如下:


//main.cpp
#include <stdio.h>
#include <vector>
#include <string>
#include "method.h"
int main() {
  using namespace std;
  //模板方法 
  string str1 = "1", str2 = "2";
  swap(str1, str2);
  printf("str1:%s, str2:%sn", str1.c_str(), str2.c_str()); 
  
  vector<int> v1, v2;
  v1.push_back(1);
  v2.push_back(2);
  swap(v1, v2);
  for (int i = 0; i < v1.size(); i++) {
    printf("v1[%d]:%dn", i, v1[i]);
  }
  for (int i = 0; i < v2.size(); i++) {
    printf("v2[%d]:%dn", i, v2[i]);
  }
  return 0;
}

vector<int>的swap代码还是比较局限,如果要用模板专门化解决所有vector的swap,该如何做呢,只需要把下面代码


template<> void swap(std::vector<int>& t1, std::vector<int>& t2) {
  t1.swap(t2);
}

改为


template<class V> void swap(std::vector<V>& t1, std::vector<V>& t2) {
  t1.swap(t2);
}

就可以了,其他代码不变。

类模板专门化

 请看下面compare代码:


//compare.h
template <class T>
 class compare
 {
 public:
 bool equal(T t1, T t2)
 {
    return t1 == t2;
 }
};

#include <iostream>
#include "compare.h"
 int main()
 {
 using namespace std;
 char str1[] = "Hello";
 char str2[] = "Hello";
 compare<int> c1;
 compare<char *> c2;  
 cout << c1.equal(1, 1) << endl;    //比较两个int类型的参数
 cout << c2.equal(str1, str2) << endl;  //比较两个char *类型的参数
 return 0;
 }

在比较两个整数,compare的equal方法是正确的,但是compare的模板参数是char*时,这个模板就不能工作了,于是修改如下:


//compare.h
#include <string.h>
template <class T>
 class compare
 {
 public:
 bool equal(T t1, T t2)
 {
    return t1 == t2;
 }
};
  

template<>class compare<char *> 
{
public:
  bool equal(char* t1, char* t2)
  {
    return strcmp(t1, t2) == 0;
  }
};

main.cpp文件不变,此代码可以正常工作。

模板类型转换

还记得我们自定义的Stack模板吗,在我们的程序中,假设我们定义了Shape和Circle类,