如何创建支持initializer_list的std::vector子类
How to create std::vector subclass with initializer_list support?
我试图创建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;
};
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 使用"std::unordereded_map"映射到"std::list"对象
- 使用std::list创建循环链表
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- "std::list::splice(std::const_iterator pos, std::list&& other)"是否保证将"其他"留空?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 内存未释放 std::list<std::shared_ptr<std::string>> C++
- 像 std::list<std::p air<string, string>> 这样的结构在返回时会被复制吗?
- std::list<std::shared_ptr>::擦除得到了一个SIGSEGV
- 将 std::list<std::unique_ptr> 移动到向量中会尝试引用已删除的函数
- C++ DLL 返回指向 std::list<std::wstring 的指针>
- 您将如何为 std::list<std::string> 创建一个类型映射,以在<String> List in C++ 中为 Java 在 SWIG 中创建?
- std::list<std::unique_ptr>:空初始值设定项列表与默认构造函数
- 错误 C2440:"=":无法从"std::list<std::string,std::分配器<_Ty>> *'转换为"std::string*"
- 无法理解如何将新对象添加到 std::list<std::unique_ptr<classname>>
- std::list<std::future>析构函数不阻塞
- 无法反序列化 std::list<std::string>