如何初始化矢量的模板化子类

How to initialise a templated sub-class of vector

本文关键字:子类 初始化      更新时间:2023-10-16

以下示例初始化向量可以正常工作:

using DataElement = std::vector<double>;
using DataVector = std::vector<DataElement>;
DataVector data;
data.emplace_back(DataElement{ 1.0f, 1.0f });
data.emplace_back(DataElement{ 1.1f, 1.1f });

现在我想使DataElement的类型成为通用的,所以我尝试了以下模板方法:

template <typename T>
class DataElement : public std::vector<T> {};
template <typename T>
class DataVector : public std::vector<DataElement<T>>{};
DataVector<double> data;
data.emplace_back(DataElement<double>{ 1.0f, 1.0f });
data.emplace_back(DataElement<double>{ 1.1f, 1.1f });

但这会在emplace_back行上生成初始化错误:no suitable constructor exists to convert from "float" to "std::vector<double, std::allocator<double>>

我对向量进行了子类化,因为这似乎是将其包装在模板中的正确方法,但由于任何其他原因,即我不需要扩展向量类功能,因此我不需要子类。

我构建向量的通用向量的方式有问题吗?

如果没问题,我如何根据我的开头示例简洁地静态初始化此数据结构的实例?

using与模板一起使用。

#include <vector>
template <typename T>
using DataElement = std::vector<T>;
template <typename T>
using DataVector = std::vector<DataElement<T>>;
int main()
{
DataVector<double> data;
data.emplace_back(DataElement<double>{ 1.0f, 1.0f });
data.emplace_back(DataElement<double>{ 1.1f, 1.1f });
}