[英]How to create std::vector subclass with initializer_list support?
我正在尝试创建从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_参数显式添加构造函数来解决此问题(请参见下面的代码),但是为什么呢? 为什么它不继承自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我不想添加此构造函数以避免编写任何其他构造函数...
因为直到您告诉构造函数,构造函数才被继承。
这不是特定于初始化列表的:
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;
};
顺便说一句,您可能希望考虑将MyVector
的Alloc
模板参数考虑MyVector
,而不是强制使用vector的默认值。
对于基类构造函数,C ++ 11允许一个类指定将继承基类构造函数。
因此,在您的情况下,可以使用std::vector<T>::vector;
指定它std::vector<T>::vector;
template <class T>
class MyVector : public std::vector<T>
{
using std::vector<T>::vector;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.