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++输入/输出运算符重载 1970-01-01
- C++按值调用 1970-01-01
- C语言访问数组元素 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 初始化变量和赋值运算符 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C++ #define 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- C++定义类对象 1970-01-01