动态检查使用可变继承的类的类型的最佳方法是什么
What is the best way to dynamically check the types of a class that uses variadic inheritance?
我正在为2D游戏引擎编写一个实体组件系统,该系统使用可变模板来构建游戏对象。这是一个对象类,它只是所有组件的容器。我去掉了不相关的东西。
template<class ... Components>
class Object : public Components...{
public:
Object(Game* game) : Components(game)...{
}
};
组件由对象继承,但我正在努力找到检查这些组件类型的最佳方法,以便它们能够正确地相互通信。例如,Physics组件将包含对象的更新位置。Drawable组件需要获得该位置,以便可以在世界上的正确位置绘制。我想在Object中添加一个更新函数,用于更新每个组件,并传输当前组件之间可以/需要传输的任何信息。
多态性是您想要的。只需制作所有组件即可:
public Object
{
enum TYPE{
COMPONENT,,
GAMEOBJECT,
ETC,,,
};
Object(TYPE id){m_id = id;}
protected:
TYPE m_id;
virtual void Update(void) = 0;
virtual void Render(void) = 0;
public:
void GetTypeOf(void)const{return m_id;}
};
class Component : Object
{
enum COMPONENT_TYPE
{
COLLIDER,
RENDERER,
ETC,,,,
};
Component() : Object (COMPONENT){/**/}
virtual void Update(void){return;}
virtual void Render(void){return;}
};
class BoxCollider : Component
{
BoxCollider(void) : Component(BOXCOLLIDER){/**/}
void Update(void)
{
//to do
}
void Render(void)
{
//to do
}
};
然后您可以简单地拥有Object*或Component*的数据结构你可以通过这种方式迭代:
std::vector<Component*>::iterator components = ComponentVector.begin();
for(;components != ComponentVector.end() ; ++components)
{
*(component)->Update();
*(component)->Render();
std::cout << "id" << *component->getTypeOf() << std::endl;
}
Object
类从其所有Components
继承,这意味着它实际上是其所有组件
您可以使用这些信息来设计update
方法
例如:
#include <cassert>
struct Game { };
struct Physics {
int position{0};
Physics(Game *) { }
void update(void *) { }
};
struct Drawable {
Drawable(Game *) { }
void update(Physics *physics) {
physics->position = 42;
}
};
template<class ... Components>
class Object: public Components... {
public:
Object(Game* game) : Components(game)... { }
void update() {
int a[] = { (Components::update(this), 0)... };
}
};
int main() {
Game game;
Object<Physics, Drawable> object{&game};
assert(object.position == 0);
object.update();
assert(object.position == 42);
}
在这里,您可以看到Drawable
在调用其update
方法时接收Physics
这种解决方案的缺点是:
- 组件的
update
方法必须获得指针参数,即使它们不需要引用任何其他组件 - 如果存在需要引用多个组件的组件,则必须获取两个或多个指针作为
update
方法的参数,或者强制转换void *
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 调用具有未标识类型的类的方法
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 我的模板类方法返回错误类型?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 构造智能点数据类型以及普通数据类型的通用方法
- 如何在没有实例的情况下获取非静态方法的类型?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 使用类型id运算符的最佳替代方法
- Java 调用 dll 字符串返回类型方法
- C++ 如何绑定和调用模板化类型方法
- 将返回类型推断为模板参数类型方法
- 返回true的模板化类型方法是在条件中进行优化的良好候选者