类模板
题目描述:实现StrBlob的模板版本。
1 /* Blob.h */ 2 #include<iostream> 3 #include<vector> 4 #include<initializer_list> 5 #include<memory> 6 using namespace std; 7 8 template <typename T> class Blob { 9 public: 10 typedef typename vector<T>::size_type size_type; 11 Blob(); 12 Blob(initializer_list<T> il); 13 14 size_type size() const { return data->size(); } 15 bool empty() const { return data->empty(); } 16 void push_back(const T &t) { data->push_back(t); } 17 void push_back(T &&t) { data->push_back(std::move(t)); } 18 19 T& back(); 20 T& front(); 21 T& operator[](size_type i); 22 private: 23 shared_ptr<vector<T>> data; 24 void check(size_type i, const T &msg); 25 }; 26 27 template <typename T> 28 Blob<T>::Blob(): data(make_shared<vector<T>()) {} 29 30 template <typename T> 31 Blob<T>::Blob(initializer_list<T> il): data(make_shared<vector<T>>(il)) {} 32 33 template <typename T> 34 void Blob<T>::check(size_type i, const T& msg) 35 { 36 if (i >= data->size()) 37 throw out_of_range(msg); 38 } 39 40 template <typename T> 41 T& Blob<T>::back() 42 { 43 check(0, "back on empty Blob"); 44 return data->back(); 45 } 46 47 template <typename T> 48 T& Blob<T>::front() 49 { 50 check(0, "front on empty Blob"); 51 return data->front(); 52 } 53 54 template <typename T> 55 T& Blob<T>::operator[](size_type i) 56 { 57 check(i, "subscript out of range"); 58 return (*data)[]; 59 }