C++primer学习:模板编程(4)

[练习]:在Blob类中用shared_pointer代替shared_ptr.

#ifndef CP5_ex16
#define CP5_ex16 
#include "iostream"
#include "fstream"
#include "sstream"
#include "vector"
#include "memory"
#include "智能指针.h"
#include "initializer_list"
#include "new"
#include "string"
using namespace std;
template<typename T> class BlobPtr;//前置声明
/***********定义类模板Blob****************/
template <typename T>class Blob
{
    friend class BlobPtr<T>;
public:
    /************给类型取别名******************/
    using size_type = typename vector<T>::size_type;
    //构造函数
    Blob() :data(std::make_shared<vector<T>>()) {};//默认初始化
    /*************** 添加接受两个迭代器的构造函数********************/
    template<typename Iter> Blob(Iter b, Iter e) : data(new vector<T>(b, e)){}

    Blob(initializer_list<T>il) : data(new vector<T>(il)){};//列表初始化
    Blob(const Blob & rhs){//拷贝初始化
        data = make_shared<vector<T>>((*rhs.data));
    }
    Blob& operator= (const Blob& rhs)
    {
        data = make_shared<vector<T>>((*rhs.data));
        return *this;
    }
    size_type size()const { return data->size(); };
    bool empty() const { return data->empty(); }
    void push_back(const T & s) { data->push_back(s); };
    T pop_back() { check(0, "pop_back on empty Blob"); data->pop_back(); };
    T& front(){ check(0, "front on empty Blob"); return data->front() };
    T& back(){ "back on empty Blob"; return data->back(); };
    const T& front()const{ check(0, "front on empty Blob"); return data->front(); };
    const T& back()const{ "back on empty Blob"; return data->back(); };
    /*********重载运算符*****************/
    const T& operator[](size_type i)const{//const版本
        check(i, "subscript out of range");
        return (*data)[i];
    }
    T& operator[](size_type i){//非const版本
        check(i, "subscript out of range");
        return (*data)[i];
    }

private:
    shared_pointer<vector<T>>data;//智能指针
    void check(size_type, const string&)const;//检查参数的正确性

};
template<typename T>
void Blob<T>::check(size_type i, const string&msg)const
{
    if (i >= data)
        throw out_of_range(msg);
}
#endif

你可能感兴趣的:(C++primer学习:模板编程(4))