C++ How to create a heterogeneous container(C++如何创建异构容器)
问题描述
我需要以 (name, value) 的形式存储一系列数据点,其中的值可以采用不同的类型.
I need to store a series of data-points in the form of (name, value), where the value could take different types.
我正在尝试为每个数据点使用一个类模板.然后对于我看到的每个数据点,我想创建一个新对象并将其推回向量中.对于每种新类型,我需要先从模板创建一个新类.但是我不能存储在任何向量中创建的对象,因为向量期望所有条目的类型相同.我需要存储的类型不能适合继承层次结构.他们是无关的.将来还会创建更多类型,我不想为每种新类型更改存储服务.有没有办法创建一个异构容器来存储这些条目?谢谢!
I am trying to use a class template for each data-point. Then for each data-point I see, I want to create a new object and push it back into a vector. For each new type, I need to create a new class from the template first. But I can not store the objects created in any vector, since vectors expect the same type for all entries. The types I need to store can not be fitted in a inheritance hierarchy. They are unrelated. Also there can be more types created in future, and I do not want to change the storage service for each new type. Is there a way to create a heterogeneous container to store these entries? Thank you!
推荐答案
boost 库可能有你正在寻找的东西(boost::any).如果您不能使用 boost,您可以使用包装指针方法自行滚动...
The boost library has probably what you're looking for (boost::any). You can roll your own using a wrapped pointer approach if you cannot use boost...
这篇关于C++如何创建异构容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++如何创建异构容器


基础教程推荐
- C语言3个整数的数组 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
- 用指数格式表示浮点数 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C++多态 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- C语言数组 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 总计将在节日礼物上花多少钱 1970-01-01