Exceptional C++

【Exceptional C++(13)】使用/滥用继承

2018-01-29  本文已影响11人  downdemo

问题

// Example 1
template <class T>
class MyList {
public:
    bool Insert(const T&, size_t index);
    T Acess(size_t index) const;
    size_t Size() const;
private:
    T* buf;
    size_t bufsize;
};
template <class T>
class MySet1 : private MyList<T>
{
public:
    bool Add(const T&); // call Insert()
    T Get(size_t index) const;
    // call Acess()
    using MyList<T>::Size;
    ...
};
template <class T>
class MySet2
{
public:
    bool Add(const T&); // call impl_.Insert()
    T Get(size_t index) const;
    // call impl_.Acess()
    size_t Size() const; // call impl_.Size()
    ...
private:
    MyList<T> impl_;
};

解答

template <class T, class Impl = MyList<T>>
class MySet3
{
public:
    bool Add(const T&); // call impl_.Insert()
    T Get(size_t index) const;
    // call impl_.Acess()
    size_t Size() const; // call impl_.Size()
    ...
private:
    Impl impl_;
};
上一篇下一篇

猜你喜欢

热点阅读