samedi 3 octobre 2015

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

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

Aucun commentaire:

Enregistrer un commentaire