if (base::empty()) return NULL; 111 return &base::front(); 112 } 113 T* back() 114 { 115 if (base::empty()) return NULL; 116 return &base::back(); 117 } 118 const T* back() const 119 { 120 if (base::empty()) return NULL; 121 return &base::back(); 122 } 123 bool is_empty() const 124 { 125 return base::empty(); 126 } 127 128private: 129 /************************************************************************************* 130 下面函数仅作内部实现,需要注意以下几点 131 (1) 不让其子类和外部可见,故使用private访问控制 132 (2) 考虑到子类可能会使用using指令来引用,如果为重载形式,子类using引用同名函数 133 会因为private出错而不能引用public同名函数,故特命名为xxx_impl而非重载形式 134 *************************************************************************************/ 135 void insert_impl(size_t index,const T& t,std::random_access_iterator_tag tag) 136 { 137 if (index < base::size()) 138 { 139 base::insert(base::begin()+index,t); 140 } 141 } 142 void insert_impl(size_t index,const T& t,std::input_iterator_tag tag) 143 { 144 if (index < base::size()) 145 { 146 typename base::iterator it = base::begin(); 147 while(index--) ++it; 148 base::insert(it,t); 149 } 150 } 151 void erase_impl(size_t index,std::random_access_iterator_tag tag) 152 { 153 if (index < base::size()) 154 { 155 base::erase(base::begin()+index); 156 } 157 } 158 void erase_impl(size_t index,std::input_iterator_tag tag) 159 { 160 if (index < base::size()) 161 { 162 typename base::iterator it = base::begin(); 163 while(index--) ++it; 164 base::erase(it); 165 } 166 } 167 void erase_impl(size_t beg,size_t end,std::random_access_iterator_tag tag) 168 { 169 end = std::min(end,base::size()); 170 if (beg < end) 171 { 172 base::erase(base::begin()+beg,base::begin()+end); 173 } 174 } 175 void erase_impl(size_t beg,size_t end,std::input_iterator_tag tag) 176 { 177 end = std::min(end,base::size()); 178 if (beg < end) 179 { 180 typename base::iterator it = base::begin(); 181 while(beg++ < end) it = base::erase(it); 182 } 183 } 184 T* get_impl(size_t index,std::random_access_iterator_tag tag) 185 { 186 if (index>=base::size()) 187 return NULL; 188 return &(*(base::begin()+index)); 189 } 190 const T* get_impl(size_t index,std::random_access_iterator_tag tag) const 191 { 192 if (index>=base::size()) 193 return NULL; 194 return &(*(base::begin()+index)); 195 } 196 T* get_impl(size_t index,std::input_iterator_tag tag) 197 { 198 if (index>=base::size()) 199 return NULL; 200 typename base::iterator it = base::begin(); 201 while (index--) ++it; 202 return &(*it); 203 } 204 const T* get_impl(size_t index,std::input_iterator_tag tag) const 205 { 206 if (index>=base::size()) 207 return NULL; 208 typename base::const_iterator it = base::begin(); 209 while(index--) ++it; 210 return &(*it); 211 } 212}; 213 214#endif 这样一来,由于STLCollection类提供了通用的操作接口,在应用时如果想切换改变为另一种容器,只需改变第2个模板参数即可,其它部分代码都不用改变,大大方便了程序的维护扩展,还可以继承STLCollection类,实现自己特殊的集合类, |