How to typeof in C++

前端 未结 8 1579
再見小時候
再見小時候 2020-12-10 18:30

How to simulate C# typeof-command behavior in C++?

C# example:

public static PluginNodeList GetPlugins (Type type)
{
 ...
}

Call:

8条回答
  •  渐次进展
    2020-12-10 18:59

    This behaviour is called RTTI (Run time type information). This technique is best to be avoided, but can be beneficial in some situations.

    There are two big ways to solve this. The first way is to write an interface with a pure virtual function that returns a class specific integer reference code. This code can then be used to represent a specific type. These integers could be stored in a specific enumeration.

    In derived classes you can then override the method and return that class specific type. During runtime, you can then call Plugin->getType() for instance, and it'll return its specific type. You can then perform a static_cast on the pointer to get the correct pointer of the derived type back.

    The second way is to either use typeid to get the classtype of the object; but this is compiler dependant. You can also try casting your pointer using dynamic_cast; dynamic_cast returns a null pointer when it's being cast into the wrong type; and a valid one when being cast in a correct type. The dynamic cast method has a bigger overhead tho than the getType method described above.

提交回复
热议问题