Ufx
Ufx

Reputation: 2695

How to derive std::vector?

I want a class derived from std::vector for my operator []

template<class T>
class MyVector : public std::vector<T>
{
public:
    // ?...

    const T &operator[](size_t index) const
        {
            //...
        }

    T &operator[](size_t index)
        {
            //...
        }
};

int main()
{
    MyVector<int> myVec = { 1, 2, 3 };
    //...
}

How can I do this deriving all std::vector constructors and assigning operators for C++11?

Upvotes: 0

Views: 492

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

Usually this is a bad idea.

First, because if someone was as silly as to new MyVector<int> and then store that in a std::vector<int> and then delete through that pointer, you have UB. But that is a pretty stupid use case; using new on std::vector is really bad code smell.

Second, because it seems pointless and confusing.

But you can do it.

template<class T>
class MyVector : public std::vector<T>
{
public:
  using std::vector<T>::vector;
  using std::vector<T>::operator=;
  MyVector(MyVector const&)=default;
  MyVector(MyVector &&)=default;
  MyVector& operator=(MyVector const&)=default;
  MyVector& operator=(MyVector &&)=default;
  const T &operator[](size_t index) const
    {
        //...
    }

T &operator[](size_t index)
    {
        //...
    }
};

now, this doesn't support construct-from std::vector<T>.

MyVector( std::vector<T>&& o ):std::vector<T>(std::move(o)) {}
MyVector( std::vector<T> const& o ):std::vector<T>(o) {}
MyVector& operator=( std::vector<T>&& o ) {
  static_cast<std::vector<T&>>(*this) = std::move(o);
  return *this;
}
MyVector& operator=( std::vector<T> const& o ) {
  static_cast<std::vector<T&>>(*this) = o;
  return *this;
}

that covers some last cases.

This won't be completely transparent, but it covers 99.9% of cases.

Upvotes: 2

Related Questions