简体   繁体   中英

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

What so? I tried adding 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)
    {
    }
};

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

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.

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM