简体   繁体   English

不同结构的列表(向量)

[英]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: 例如在MFCCObjectCArray但没有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::anyboost::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: 您可以至少通过两种不同的方式安全地进行此操作:

  • All the objects can inherit from a common base which has a virtual destructor. 所有对象都可以从具有virtual析构函数的通用库中继承。 You can then make a std::vector of std::unique_ptr s to the common base. 然后,您可以将std::unique_ptrstd::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指向)。
  • You can use a variant type like 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM