C++: converting a container to a container of different yet compatible type

后端 未结 8 1014
南笙
南笙 2021-01-05 08:28

It often happens to me to have a a container C (or whatever kind of wrapper class, even smart pointers) for a type T1, and want to convert such

8条回答
  •  没有蜡笔的小新
    2021-01-05 09:09

    This is indeed difficult for containers. Type compatibility is not enough, types actually need to be identical in memory to prevent slicing when assigning. It might be possible to implement a ptr_container that exposes pointers of a compatible type. For example, boost's ptr_containers keep void*s internally anyways, so casting them to compatible pointers should work.

    That said, this is definitely possible with smart pointers. For example, boost::shared_ptr implements static_pointer_cast and dynamic_pointer_cast.

提交回复
热议问题