C++ collection of abstract base classes

一笑奈何 提交于 2019-12-12 01:32:02

问题


how can I create STL collection of classes which implement abstract base class using the base class as collection value, without using pointers?

is there something in Boost that allows me to implement it? The collection specifically is map.

Thanks


回答1:


You cannot avoid pointers completely. You must store pointers in the collection if you want to avoid Object slicing. Boost has a container that hides the pointers pretty well: ptr_map




回答2:


The Boost Pointer Container Library does what you want.




回答3:


You can't

Think about how the compiler would generate code to do that ? No pointers means that the storage has to be allocated "in the collection itself" in a static array or something. But the storage required for the subclasses can change ! So how would the compiler do it ? ... it can't ...



来源:https://stackoverflow.com/questions/1776993/c-collection-of-abstract-base-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!