c++ - 动态转换、对象列表转换、模板

标签 c++ templates dynamic-cast

有两个类:

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/

相关文章:

c++ - 如何通过交叉广播恢复接口(interface)

c++ - 将 C++ std::Vector 传递给 Python 中的 numpy 数组

c++ - 跨多个命名空间的 clang 错误 "explicit instantiation does not refer to a function template"

java - 动态类型转换 : Class and String to Comparable

c++ - 动态 Actor - 两者之间的区别

c++ - 相同的字符串到多个流

c++ - 当 img(roi) 未返回正确值时如何正确提取 ROI

javascript - 使用 Handlebars.js 模板

c++ - 如何在C++中使用 "type ... pack-name"参数包?

c++ - 为什么 const 模板化引用类型不同于 const 引用类型?