在 std::vector 中使用结构来推送多个类型有什么问题?
What is wrong with using struct for pushing multiple types in std::vector?
>我正在尝试将多个类型推入同一个std::vector
。例如,假设我想将class type1
和class type2
推送到向量中。
所以基本上我能够做到:
vec.push_back(new type1, new type2);
vec.push_back(new type1, new type2);
我想到的是,通过使它们从父类类型继承来使 type1 和 type2 具有相同的类型(但我现在没有这种奢侈)。
所以我求助于使用struct
.所以我所做的是
struct type{
type1* t1;
type2* t2;
};
std::vector<type> vec;
vec.push_back({new type1, new type2});
您认为为此使用结构是一个好主意还是我应该使用这篇文章建议的技术?我关于该帖子的另一个问题,为什么要让它变得复杂而不是像我一样只使用struct
?
编辑:另一种方法是使用std::vector<std::pair <type1, type2>>
但是由于我可能也有type3,因此这仍然对我不起作用。
编辑我所说的type1
和type2
是point
和triangle
。
在评论部分编辑马丁的答案:我现在计划使用tuple with combining with enum
查看更多详细信息。
注释中的具体答案:then you could template it to the types using std::tuple instead of std::pair, as std::vector<std::tuple<type1, type2,.. typen>> m_types
这是一个好主意,尽管您没有从多态性中获利。我知道您不能更改 type1 和 type2 类,但您可以围绕它们包装一个适合您需求的类:
(未测试)
class TypeWrap
{
public:
virtual void execute() = 0;
};
class Type1Wrap : public TypeWrap
{
private:
Type1 m_type;
public:
void execute(){ m_type.execute(); }
};
class Type2Wrap : public TypeWrap
{
private:
Type2 m_type;
public:
void execute(){ m_type.execute(); }
};
然后使用允许您调用m_types[0]->execute();
的vector<TypeWrap*> m_types
作为旁注,直接使用新运算符的不良做法(在一般意义上),如果您需要动态分配,或者只是使用Type1Wrap type; m_types.push_back(&type);
来获取指向对象的指针,则其他选项(如 unique_ptr 或 shared_ptr)更好,但请确保保持对象处于活动状态!
- 我应该使用什么来代替void作为变体中的替代类型之一
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 数据类型"struct seq<0, 1, 2>{}"含义是什么?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 您应该在什么时候创建自己的异常类型
- C++ 未初始化的本地(非全局)int 数组中的元素类型到底是什么?
- 未命名的非类型模板参数有什么意义?
- 静态自动 constexpr t = { "red" , "black" , "green" } 是什么类型;派生到?
- 模板<>模板<类型名 T> 语法有什么用?
- 指针类型类成员的动态强制转换的恒定性是什么?
- 当 c++ 需要一种数据类型并获取另一种数据类型时会发生什么?
- 这是什么类型的C++语法,我应该采取什么步骤来理解这一点
- 返回类型在 C++ OOP 中是什么意思
- 如何声明一个标准::提升直方图的向量?提升直方图的类型是什么?
- 类名后跟括号的类型是什么
- 删除对象(具有不同类型)的引用时会发生什么情况?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 当你只使用 return 时,函数返回什么类型;在 c++ 中