STL运用的C++技术(1)——成员模板

来源:互联网 发布:软件项目质量保证方案 编辑:程序博客网 时间:2024/05/29 02:24

 STL是C++标准库的重要组成部分之一,它不仅是一个可复用的组件库,更是一个包含算法与数据结构的软件框架,同时也是C++泛型编程的很好例子。STL中运用了许多C++的高级技术。本文介绍成员模板的运用。主要参考了《C++ Primer》和《STL源码剖析》。

         成员模板 member template

         任意类(模板或非模板)可以拥有本身为类模板或函数模板的成员,这种成员称为成员函数模板。STL中为什么要运用这种技术呢?考虑 vector 容器的 assign 成员函数,它可以接受两个迭代器为容器赋值,而这两个迭代器可以是 list 的迭代器、deque的迭代器、甚至是两个原生指针。也就是说成员函数 assign 的形参是不确定的。解决的方法是使用模板形参来表示迭代器形参的类型。下面给出一段小程序,使用成员模板技术。

[cpp] view plaincopyprint?
  1. #include <iostream>  
  2. #include <list>  
  3. using namespace std;  
  4.   
  5. //自定义  
  6. class MyAlloc{  
  7. };  
  8.   
  9. template <class T, class Alloc = MyAlloc>  
  10. class MyVector  
  11. {  
  12. public:  
  13.     typedef T value_type;  
  14.     typedef value_type* iterator;  
  15.     //成员模板,接受各种迭代器  
  16.     template <class I>  
  17.     void assign(I first, I last)  
  18.     { cout<<"assign"<<endl; }  
  19. };  
  20.   
  21. int main()  
  22. {  
  23.     MyVector<int> v;  
  24.     int a[] = {1, 2, 3};  
  25.     list<int> l(a, a + 3);  
  26.     v.assign(a, a + 3);           //原生指针  
  27.     v.assign(l.begin(), l.end()); //链表迭代器  
  28.     return 0;  
  29. }  

         STL中另一个模板例子是接受两个迭代器的容器构造函数。下面给出了一个小程序。

[cpp] view plaincopyprint?
  1. #include <iostream>  
  2. #include <list>  
  3. using namespace std;  
  4.   
  5. //自定义  
  6. class MyAlloc{  
  7. };  
  8.   
  9. template <class T, class Alloc = MyAlloc>  
  10. class MyVector  
  11. {  
  12. public:  
  13.     typedef T value_type;  
  14.     typedef value_type* iterator;  
  15.   
  16.     template <class I>  
  17.     MyVector(I first, I last)  
  18.     { cout<<"MyVector"<<endl; }  
  19. };  
  20.   
  21. int main()  
  22. {  
  23.     int a[] = {1, 2, 3};  
  24.     list<int> l(a, a + 3);  
  25.     MyVector<int> v(a, a + 3);             //原生指针  
  26.     MyVector<int> v2(l.begin(), l.end());  //链表迭代器  
  27.     return 0;  
  28. }  

        上面程序中类的内部定义成员模板,如果要在外面定义成员模板,必须包含两个模板形参表,类模板形参和自己的模板形参。首先是类模板形参表,然后是自己的模板形参表。

[cpp] view plaincopyprint?
  1. #include <iostream>  
  2. #include <list>  
  3. using namespace std;  
  4.   
  5. //自定义  
  6. class MyAlloc{  
  7. };  
  8.   
  9. template <class T, class Alloc = MyAlloc>  
  10. class MyVector  
  11. {  
  12. public:  
  13.     typedef T value_type;  
  14.     typedef value_type* iterator;  
  15.     template <class I>  
  16.     MyVector(I first, I last);  
  17.     template <class I>  
  18.     void assign(I first, I last);  
  19. };  
  20. template<class T, class Alloc> template <class I>  
  21. MyVector<T, Alloc>::MyVector(I first, I last)  
  22. {   
  23.     cout<<"MyVector"<<endl;   
  24. }  
  25. template<class T, class Alloc> template <class I>  
  26. void MyVector<T, Alloc>::assign(I first, I last)  
  27. {   
  28.     cout<<"assign"<<endl;   
  29. }  
0 0