类模板

题目描述:实现StrBlob的模板版本。

 /*    Blob.h    */
#include<iostream>
#include<vector>
#include<initializer_list>
#include<memory>
using namespace std; template <typename T> class Blob {
public:
typedef typename vector<T>::size_type size_type;
Blob();
Blob(initializer_list<T> il); size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
void push_back(const T &t) { data->push_back(t); }
void push_back(T &&t) { data->push_back(std::move(t)); } T& back();
T& front();
T& operator[](size_type i);
private:
shared_ptr<vector<T>> data;
void check(size_type i, const T &msg);
}; template <typename T>
Blob<T>::Blob(): data(make_shared<vector<T>()) {} template <typename T>
Blob<T>::Blob(initializer_list<T> il): data(make_shared<vector<T>>(il)) {} template <typename T>
void Blob<T>::check(size_type i, const T& msg)
{
if (i >= data->size())
throw out_of_range(msg);
} template <typename T>
T& Blob<T>::back()
{
check(, "back on empty Blob");
return data->back();
} template <typename T>
T& Blob<T>::front()
{
check(, "front on empty Blob");
return data->front();
} template <typename T>
T& Blob<T>::operator[](size_type i)
{
check(i, "subscript out of range");
return (*data)[];
}
05-10 22:24
查看更多