std::vector或其他数据结构中不同类型的对象
different types of objects in std::vector or another data structure
我想存储这样的结构
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方法)时,您总是必须知道要向下转换到什么类型。
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 如何使用nullptr初始化同一类对象的静态指针数组?
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- RocksDB是存储同质对象的好选择吗
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象