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++如何创建异构容器
- 使用整数值初始化char类型的变量 1970-01-01
- 打印扩展的ASCII字符 1970-01-01
- C++指向数组的指针 1970-01-01
- C语言求模 1970-01-01
- 使用最流行的转义序列 1970-01-01
- C语言可使用的所有转义序列 1970-01-01
- 使用来自float.h和limits的数据,找到该系统的一些 1970-01-01
- 运算符优先级 1970-01-01
- “纯虚函数调用"在哪里?崩溃从何而来? 2022-10-18
- C++浮点常数 1970-01-01