模板调用之间的C ++强制转换 [英] C++ Casting between template invocations

查看:69
本文介绍了模板调用之间的C ++强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 X< T> 是一个模板类,以一个类作为参数,并以 A B 是类,其中 B 是从 A 派生的,而没有多个或虚拟的参与继承(即在 A B 之间进行转换时,无需进行指针调整)。

suppose X<T> is a template class taking a class as parameter and A and B are classes with B being derived from A without involvement of multiple or virtual inheritance (i.e. no pointer adjustments necessary when casting between A and B).

执行从 X< A *> X< B *>的链锯重新解释是否安全? code>或相反?当然, X< A *> 不是 X< B *> ,但这些不应该类总是共享相同的行为?因为使用了指针,所以内存布局应该相等。因此,可以让 X< B *> 的方法在实际上是 X< A *<

is it safe to perform a chainsaw reinterpret cast from X<A*> to X<B*> or vice versa? Of course, a X<A*> is no X<B*>, but shouldn't these classes always share the same behaviour? Because pointers are used, the memory layout should be equal. Thus, it might be okay to let methods of X<B*> operate on an instance which is actually an X<A*>.

当然,这会以某种方式破坏类型安全性,例如,我可以将 A * 元素插入到 X< B *> ,但这不在此问题的范围内。

Of course, this somehow ruins type safety as I could for example insert an element of A* into an X<B*>, but this is out of the scope of this question.

推荐答案

如果确实需要,最好写这样的东西。

It's better to write something like this, if you REALLY need it.

X<A*> a(new B());
X<B*> b( dynamic_cast<B*> ( a.get_pointer() ) );
if(b.get_pointer() != NULL)
{
    ...
}

这篇关于模板调用之间的C ++强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆