如何使用initializer_list支持创建std :: vector子类?

时间:2015-10-03 16:58:39

标签: c++ c++11 stdvector initializer-list

我正在尝试创建继承自 std :: vector MyVector 类(添加一些有用的方法)。一切都很好,但无法用_initializer_list _:

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

VS2015和gcc都不允许编译它:

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

怎么样?我尝试使用_initializer_list_ param明确添加构造函数来解决问题(参见下面的代码),但为什么呢?为什么它不继承自 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。我不想添加这个构造函数以避免编写任何其他构造函数...

2 个答案:

答案 0 :(得分:5)

因为构造函数在你告诉它们之前不会被继承。

这不是特定于初始化列表:

struct A
{
   A() = default;
   A(int x) {}
};

struct B : A
{};

int main()
{
   B b{3};   // nope!
}

使用using语句继承构造函数,如下所示:

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

顺便说一句,您可能希望将Alloc模板参数考虑到MyVector,而不是强制使用向量的默认值。

答案 1 :(得分:0)

对于基类构造函数,C ++ 11允许类指定将继承基类构造函数。

因此,在您的情况下,您可以使用std::vector<T>::vector;

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