Can i somehow copy member types from vector?

Viewed 86

I am writing MyVector class which has std::vector as private field. And MyVector class should provide all the member types of std::vector. How can i solve this problem? Is a correct way to copy them like this(but it doesn't work):

class MyVector{
    private:
        vector<int> numbers;
    public:
        using value_type = vector<int>::value_type;
        using size_type = vector<int>::size_type;
        using iterator = vector<int>::iterator;
        using allocator_type = vector<int>::allocator_type;
        using difference_type = vector<int>::difference_type;
        using reference = vector<int>::reference;
        using const_reference = vector<int>::const_reference;
        using pointer = vector<int>::pointer;
        using const_pointer = vector<int>::const_pointer;
        using const_iterator = vector<int>::const_iterator;
        using reverse_iterator = vector<int>::reverse_iterator;
        using const_reverse_iterator = vector<int>::const_reverse_iterator;
};
2 Answers

There's no way to do this.

You can either inherit all the members of std::vector by publicly inheriting it and understanding how to cope with the lack of virtual destructor (thank you @M.A), or you can pick & choose as you are doing. There is no other way to specify which members to inherit.

But my personal advice is not to inherit std::vector. Better to be explicit about what you want to "inherit" and do as you're doing. Our goal should not be to save keystrokes.

If you want to selectively use parts of the std::vector you can always use private inheritance and expose those functions you want in your derived public interface:

template<typename T>
class MyVector
: private std::vector<T>
{
private:
    using base_type = std::vector<T>;

public:
    using base_type::value_type;
    using base_type::iterator;
    using base_type::pointer;
    using base_type::reference;
    // ... etc ...

    using base_type::begin;
    using base_type::end;
    using base_type::operator[];
    // ... etc ...

};
Related