Sto*_*eys 0 c++ stdvector initializer-list c++11
我正在尝试创建继承自std :: vector的MyVector类(添加一些有用的方法).一切都很好,但无法使用_initializer_list_进行初始化:
std::vector<int> a = { 4, 2 }; // OK
MyVector<int> b = { 4, 2 }; // Error
Run Code Online (Sandbox Code Playgroud)
VS2015和gcc都不允许编译它:
error: could not convert '{2, 3, 4}' from '<brace-enclosed initializer list>' to 'MyVector<int>'
Run Code Online (Sandbox Code Playgroud)
那又怎样?我尝试使用_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)
{
}
};
Run Code Online (Sandbox Code Playgroud)
PS我不想添加这个构造函数,以避免编写任何其他构造函数...
因为构造函数在你告诉它们之前不会被继承.
这不是特定于初始化列表:
struct A
{
A() = default;
A(int x) {}
};
struct B : A
{};
int main()
{
B b{3}; // nope!
}
Run Code Online (Sandbox Code Playgroud)
使用using语句继承构造函数,如下所示:
template <class T>
class MyVector : public std::vector<T>
{
using std::vector<T>::vector;
};
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可能希望考虑Alloc模板参数MyVector,而不是强制使用向量的默认值.
| 归档时间: |
|
| 查看次数: |
646 次 |
| 最近记录: |