问题描述
我希望有一个从类到每个类的实例的映射。目标是具有用于基于组件的游戏引擎的组件的容器,其中对象可以具有每个组件类型的至多一个。
I wish to have a map from classes to instances of each class. The goal is to have a container of components for a component-based game engine where an object can have at most one of each component type.
在Java中,我只能使用类对象作为键。如何在C ++中做类似的事情?我最初的研究建议像使用typeid(component_instance).name()作为键。
In Java, I could just use class objects as the key. How can I do something similar in C++? My initial research suggests something like using typeid(component_instance).name() as the key. Is there a better way to do this?
推荐答案
与更多动态语言(如Python或Java)不同,C ++中的类不是对象他们自己。在运行时它们根本不存在(就程序员的观点而言)。
Unlike in more dynamic languages like Python or Java, classes in C++ are not objects themselves. At runtime they merely do not exist (as for a programmers point of view).
您的 typeid
但是对于性能问题,我会使用哈希或数字ID(类似于在类中定义为静态的整数)而不是字符串。
Your typeid
approach is not that bad, but for performance issues I'd use a hash or a numeric ID (like an integer defined as static in your class) instead of the string.
这篇关于如何将类类型映射到C ++中的类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!