Why is RTTI necessary?

后端 未结 2 1389
一生所求
一生所求 2021-01-07 06:34

Why is RTTI (Runtime Type Information) necessary?

2条回答
  •  走了就别回头了
    2021-01-07 06:46

    RTTI, Run-Time Type Information, introduces a [mild] form of reflection for C++.

    It allows to know for example the type of a super class, hence allowing to handle an heterogeneous collection of objects which are all derived from the same base type. in ways that are specific to the individual super-classes. (Say you have an array of "Vehicle" objects and need to deal differently with the "Truck" objects found amid the array).

    The question whether RTTI is necessary is however an open one. Story has it that Bjarne Stroustrup purposefully excluded this feature from the original C++ specification, by fear that it would be misused.
    There are indeed opportunities to overuse/misuse reflection features, and this may have been even more of a factor when C++ was initially introduced because there wasn't such a OOP culture in the mainstream programmer community.
    This said, with a more OOP savvy community, with the effective demonstration of all the good things reflection can do (eg. with languages such as Java or C#) and with the fancy design patterns in use nowadays, I strongly believe that RTTI and reflection features at large are very important even if sometimes misused.

提交回复
热议问题