我正在尝试创建继承自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我不想添加这个构造函数,以避免编写任何其他构造函数...