C++ template一些体悟(3)

其实没啥体悟,因为还没有感受到这些例子的作用,记一下先

 1 #include <iostream>
 2 
 3 using namespace std;
 4 class alloc {
 5 
 6 };
 7 
 8 template<class T, class Alloc = alloc>
 9 class vector {
10 public:
11     void swap(vector<T, Alloc>&) {
12         cout << "swap()" << endl;
13     }
14 };
15 
16 template<class T,class Alloc>
17 inline void swap(vector<T, Alloc>& x,vector<T, Alloc>& y){
18     x.swap(y);
19 }
20 
21 
22 int main(int argc, char **argv) {
23     vector<int> x,y;
24     swap(x,y);
25     return 0;
26 }

 以下用于验证class template内能否在有template

 1 #include <iostream>
 2 
 3 using namespace std;
 4 class alloc {
 5 
 6 };
 7 
 8 template<class T, class Alloc = alloc>
 9 class vector {
10 public:
11     typedef T value_type;
12     typedef value_type* iterator;
13   //测试class template内能否再有template
14     template<class I>
15     void insert(iterator position, I first, I last) {
16         cout << "insert()" << endl;
17     }
18 };
19 
20 int main(int argc, char **argv) {
21     int ia[5] = { 0, 1, 2, 3, 4 };
22 
23     vector<int> x;
24     vector<int>::iterator ite;
25     x.insert(ite, ia, ia + 5);
26     return 0;
27 }

测试template参数可否根据前一个template参数而设定默认值

 1 #include <iostream>
 2 #include <cstddef>
 3 
 4 using namespace std;
 5 
 6 class alloc {
 7 
 8 };
 9 
10 template<class T, class Alloc = alloc, size_t BufSiz = 0>
11 class deque {
12 public:
13     deque() {
14         cout << "deque" << endl;
15     }
16 };
17 
18 template<class T, class Sequence = deque<T>>
19 class stack {
20 public:
21     stack() {
22         cout << "stack" << endl;
23     }
24 private:
25     Sequence c;
26 };
27 
28 int main(int argc, char **argv) {
29     stack<int> x;
30     return 0;
31 }

运行结果:

deque
stack

 先成员变量构造,再构造函数。

猜你喜欢

转载自www.cnblogs.com/Jacket-K/p/9264222.html