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

后端 未结 8 996
南笙
南笙 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 08:47

    The reason you can't cast the containers has nothing to do with the types themselves. The problem is that you're trying to cast two objects that are, as far as the compiler and linker are concerned, two unrelated classes.

    When you do C and C, for example, the compiler emits code like this:

    class C_int_ {
        //...
    };
    
    class C_short_ {
        //...
    };
    

    Since these classes are obviously unrelated, you can't cast them. And if you force it (eg, using a C cast), and it has any virtual functions, you will likely blow something up.

    Instead, you have to do it manually, using a loop. Sorry.

提交回复
热议问题