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

后端 未结 8 958
南笙
南笙 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:05

    Moreover for many cases I'm pretty sure that forcing a reinterpret_cast would work fine

    I’m betting you that it doesn’t. Two containers that store different types are never guaranteed to be binary compatible even if their contained objects are. Even if they happen to be binary compatible under some specific version of some compiler implementation, this is an implementation detail that can change from one minor version to the next.

    Relying on such undocumented behaviour is opening the door to many unpleasantly long nights of debugging.

    If you want to pass such containers to a function, simply make the function a template so that containers of arbitrary type can be passed into it. Similar with classes. This is the whole point of templates, after all.

提交回复
热议问题