Search code examples
c++c++11stdvectorinitializer-list

How to create std::vector subclass with initializer_list support?


I'm trying to create MyVector class that inherits from std::vector (to add a few useful methods). Everything works great, but it cannot be initialized with initializer_list:

    std::vector<int> a = { 4, 2 }; // OK
    MyVector<int> b = { 4, 2 }; // Error

Both VS2015 and gcc does not allow compiling it:

error: could not convert '{2, 3, 4}' from '<brace-enclosed initializer list>' to 'MyVector<int>'

Why so? I tried explicitly adding constructor with initializer_list param solves the issue (see code below), but why?? Why isn't it inherited from std:vector?

template <class T>
class MyVector : public std::vector<T>
{
public:
    // Why is this constructor needed???
    MyVector(const std::initializer_list<T>& il)
        : std::vector<T>(il)
    {
    }
};

P.S. I don't want to add this constructor to avoid writing any other constructors...


Solution

  • Because constructors aren't inherited until you tell them to be.

    This is not specific to initializer-lists:

    struct A
    {
       A() = default;
       A(int x) {}
    };
    
    struct B : A
    {};
    
    int main()
    {
       B b{3};   // nope!
    }
    

    Inherit constructors with the using statement, like so:

    template <class T>
    class MyVector : public std::vector<T>
    {
       using std::vector<T>::vector;
    };
    

    By the way, you may wish to consider an Alloc template parameter to MyVector, instead of forcing the use of vector's default.