C ++如何创建异构容器 [英] C++ How to create a heterogeneous container

查看:464
本文介绍了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 ++如何创建异构容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆