如何通常实现dynamic

如何通常实现dynamic

本文介绍了如何通常实现dynamic_cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型检查是一个整数比较吗?或者有一个 > dynamic_cast 远远超出了简单的类型检查。如果它只是一个类型检查,它将很容易实现(类似于你在你的原始帖子)。



除了类型检查, dynamic_cast 可以执行转换到 void * 和分层交叉。这些类型的转换在概念上需要一些能力在两个方向(上和下)中遍历类层次结构。支持这样的转换所需的数据结构比单纯的标量类型id更复杂。 dynamic_cast 正在使用的信息是RTTI的一部分。



尝试在此处描述它将会适得其反。我曾经有一个很好的链接描述一个可能的实现RTTI ...将尝试找到它。


Is the type check a mere integer comparison? Or would it make sense to have a GetTypeId virtual function to distinguishing which would make it an integer comparison?

(Just don't want things to be a string comparison on the class names)

EDIT: What I mean is, if I'm often expecting the wrong type, would it make sense to use something like:

struct Token
{
    enum {
        AND,
        OR,
        IF
    };
    virtual std::size_t GetTokenId() = 0;
};

struct AndToken : public Token
{
    std::size_t GetTokenId() { return AND; }
};

And use the GetTokenId member instead of relying on dynamic_cast.

解决方案

The functionality of the dynamic_cast goes far beyond a simple type check. If it was just a type check, it would be very easy to implement (something like what you have in your original post).

In addition to type checking, dynamic_cast can perform casts to void * and hierarchical cross-casts. These kinds of casts conceptually require some ability to traverse class hierarchy in both directions (up and down). The data structures needed to support such casts are more complicated than a mere scalar type id. The information the dynamic_cast is using is a part of RTTI.

Trying to describe it here would be counterproductive. I used to have a good link that described one possible implementation of RTTI... will try to find it.

这篇关于如何通常实现dynamic_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:45