C++ Casting between template invocations

谁说我不能喝 提交于 2019-12-11 16:25:49

问题


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).

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*>.

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.


回答1:


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)
{
    ...
}



回答2:


No you can't. If B is of a polymorphic class casting B* to A* might change the value of the pointer. Generally speaking using reinterpret_cast is never safe, and if still you need it, then you probably wrote something wrong (There are some cases, where you need to you it, but this isn't one of them).

And by the way, templates can be specialized on template parameters, so X and X might not even have the same internal structure.



来源:https://stackoverflow.com/questions/10894295/c-casting-between-template-invocations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!