你好!
C++ 问题!
我想检查(在C++中)包含抽象类型 A 的对象的向量是否包含 B 类型的对象,其中 B 是从 A 派生的类。
为什么?
我需要这个的原因是我试图在C++中实现一个基本的实体组件系统。
因此,每个组件类型都将派生自一个抽象类,这将让我将它们全部存储在同一个向量中。
但我确实需要某种方式来了解实体附加了哪些类型的组件。所以我也需要某种区分方式,而这正是我真正需要帮助的地方!
这是一个示例代码,非常简单地说明了我要实现的内容:
class Component
{}
class Rigidbody : public Component
{}
class Mesh : public Component
{}
……
class ContainerClass
{
public:
template<typename T>
bool contains(const T element) const
{
//Return whether or not elements contains an element of type T.
//which has to be a class derived from the Component class,
//but not of abstract type "Component".
//I also need a way of making sure T can only be of a type derived from Component.
}
inline void add(const Component &p_Component)
{
m_Components.push_back(p_Component);
}
private:
vector<Component> m_Components;
}
所以在:
ContainerClass test;
B b;
test.add(b);
test.contains(B); 应该是真的。
test.contains(C); 应该是假的。
顺便说一句,我知道 StackOverflow 中有一些与此问题类似的问题,但我看到的每一个解决方案都是特定于编程语言的,不适用于 C++。
至少据我所知。
谢谢!