StoneyKeys
StoneyKeys

Reputation: 138

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...

Upvotes: 2

Views: 1472

Answers (2)

basav
basav

Reputation: 1495

For base-class constructors, C++11 allows a class to specify that base class constructors will be inherited.

so, in your case, you could specify it by using std::vector<T>::vector;

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

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

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.

Upvotes: 7

Related Questions