[英]List (vector) of different structs
is it possible to have some kind of list / array / vector of different structs? 是否可能有某种不同结构的列表/数组/向量?
For example in MFC
there are CObject
and CArray
but without MFC: 例如在
MFC
有CObject
和CArray
但没有MFC:
I can do something alike 我可以做些类似的事情
std::vector<void*> pVec;
{
MYSTRUCT m = new MYSTRUCT;
pArr.push_back(m);
// looks fine here
}
//what is in my vector now?
Is there something that can handle it? 有什么可以应付的吗?
The obvious preferred approach is to have a std::vector<Base*>
to handle polymorphic types. 明显的首选方法是让
std::vector<Base*>
处理多态类型。
If you really have completely unrelated types, as it seems to be the case, then boost::any
or boost::variant
type erasers might be what you are looking for : 如果确实确实存在完全不相关的类型(看起来确实如此),那么您可能正在寻找
boost::any
或boost::variant
类型的橡皮擦:
std::vector< boost::variant<int, std::string> > vec;
vec.push_back( 21 );
vec.push_back( "hello " );
The example that you have given is dangerous. 您所举的例子很危险。 How do you clean up (ie
delete
) what you've allocated? 您如何清理(即
delete
)分配的内容? Its type has been erased by being assigned to a void *
, so how can the compiler know which operator delete
to call? 它的类型已通过分配给
void *
而被擦除,那么编译器如何知道要operator delete
?
You can safely go about this at least two different ways: 您可以至少通过两种不同的方式安全地进行此操作:
virtual
destructor. virtual
析构函数的通用库中继承。 You can then make a std::vector
of std::unique_ptr
s to the common base. std::unique_ptr
的std::vector
设为通用基数。 This has the advantage of being extensible (you can declare new types which derive from the common base and throw them in the container without modifying the container), but has the disadvantage of requiring that you go to the free store (to allocate memory for the std::unique_ptr
s to point to). std::unique_ptr
指向)。 boost::variant
. boost::variant
类的变量类型。 This will not require a common base, or allocations on the free store, but it will require that you declare all the types that can possibly be stored in the container when you declare the container (ie it's not as easily extensible as an inheritance-based solution).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.