我试图创建MyVector类继承自std::vector(添加一些有用的方法)。一切都很好,但是不能用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)
{
}
};
注:我不想添加这个构造函数,以避免编写任何其他构造函数…
因为构造函数是不会被继承的,除非你告诉它们。
这不是特定于初始化列表:
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
,而不是强制使用vector的默认值。
对于基类构造函数,c++ 11允许一个类指定将继承基类构造函数。
所以,在您的情况下,您可以使用std::vector<T>::vector;
template <class T>
class MyVector : public std::vector<T>
{
using std::vector<T>::vector;
};