有两个类:
class A
{
private:
double a1, a2;
...
};
class B : public A
{
private:
double b1, b2;
};
和一个通用容器
template <typename Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <typename Item>
class GList
{
private:
typename TList <Item>::Type items;
};
有4个对象容器
GList <A> A1;
GList <B> B1;
GList <A*> A2;
GList <B*> B2;
是否允许这些转换(向上/向下):
1] GList <B> B3 = dynamic_cast <GList <B> &> (A1);
2] GList <A> A3 = static_cast <GList <A> &> (B1);
3] GList <B*> B4 = dynamic_cast <GList <B*> &> (A2);
4] GList <A*> A4 = static_cast <GList <A*> &> (B2);
有没有办法将对象列表转换为父对象列表,反之亦然?
更新问题
那么 reinterpret_cast 呢?
1] GList <B> B3 = reinterpret_cast <GList <B> &> (A1);
2] GList <A> A3 = reinterpret_cast <GList <A> &> (B1);
3] GList <B*> B4 = reinterpret_cast <GList <B*> &> (A2);
4] GList <A*> A4 = reinterpret_cast <GList <A*> &> (B2);
最佳答案
从根本上说,容器不是协变的; std::vector<Base>
之间没有关系和 std::vector<Derived>
(也不在 std::vector<Base *>
和 std::vector<Derived *>
之间。
在值类型容器的情况下,通常存在一个基本问题,sizeof(Derived) > sizeof(Base)
.所以 std::vector
中的所有内部指针数学运算如果您试图将其中一个强加给另一个,将会严重崩溃。
在指针类型容器的情况下,这些转换可能“有效”(如果您可以让它们编译),但行为是未定义的。
关于c++ - 动态转换、对象列表转换、模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5051264/