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

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

    It's absolutely not guaranteed that those containers are binary compatible and could be casted with something like reinterpret_cast<>.

    For example, if the container (like std::vector) stores the data internally in a C-style array, C would contain a T1[] array while C would contain a T2[]. If now T1 and T2 have different sizes (for example T2 has more member variables) the memory of the T1[] can not simply be interpreted as a T2[] since the elements of these arrays would be located at different positions.

    So simply interpreting the C memory as a C won't work and a real conversion is necessary.

    (Furthermore there might be template specializations for different types, so that C might look completely different than C)

    For converting one container to another see for example this question or many other related ones.

提交回复
热议问题