std::vector或其他数据结构中不同类型的对象

different types of objects in std::vector or another data structure

本文关键字:同类型 对象 数据结构 vector 其他 std      更新时间:2023-10-16

我想存储这样的结构

  template <typename var_type> struct
  {
  int some_var;
  //...some antoher vars
  var_type problem_var;
  };

在向量或类似向量的东西中,我怎么能做到呢?我无法创建带有模板内容的向量

如果事先知道类型列表,boost::variant<>可能比boost::any更合适。在您的情况下,您可能需要

typedef boost:variant<
   mystruct<float>,
   mystruct<int>
   mystruct<std::string>
> my_variant;

这将只允许这3种类型。或者,您可能需要mystruct<boost:variant<float, int, std::string> >,它在表面上是相似的。我无法从你的问题中判断哪一个最适合你的问题。

您可以使用类似Boost.Any.的东西

难道不能用需要存储的对象类型创建一个类层次结构,并在插入向量时始终向上转换到基类吗?

缺点是,当从向量中提取项或使用基类接口(可能是getter方法)时,您总是必须知道要向下转换到什么类型。