如何使用模板继承和组件

How to use template inheritance and components

本文关键字:组件 继承 何使用      更新时间:2023-10-16

我正在尝试将组件模式与模板一起使用:

template <typename ComponentGraphics>
struct Object {
ComponentGraphics* graphics;
// there is other components as well
Object(ComponentGraphics* _graphics) : graphics(_graphics) {};
void update() {
graphics->update(this); //Error occure there
};
};

然后我用一个类Player继承它:

class Player : public Object<PlayerGraphics> {
using Object::Object;
public:
sf::Vector2f position;
};

使用PlayerGraphics.h:

class Player;
class PlayerGraphics{
public:
void update(Player* parent);
};

PlayerGraphics.cpp:

#include "Player.h"
void PlayerGraphics::update(Player* parent) {
// Process inputs and update parent
}

实际问题:然后我从PlayerGraphics调用update(Player*parent(方法我得到错误无法从'Object<PlayerGraphics>*'到"Player*">

对我来说,问题来自于继承,尽管我找不到自己做错了什么。

不能将基类隐式转换为派生基类。演员阵容应该是明确的。

例如:

struct PlayerGraphics {
using Parent = Player;
void update(Parent* parent);
};
template<typename ComponentGraphics>
struct Object {
void update() {
using Parent = typename ComponentGraphics::Parent;
graphics->update(static_cast<Parent*>(this));
};
};

或使用类型特征:

template<typename ComponentGraphics>
struct Traits;
template<>
struct Traits<PlayerGraphics> {
using Parent = Player;
};
template<typename ComponentGraphics>
struct Object {
void update() {
using Parent = typename Traits<ComponentGraphics>::Parent;
graphics->update(static_cast<Parent*>(this));
};
};

注意,ComponentGraphicsObject内部的不完全类型,其使用受到限制。例如,可以在update()正文中使用typename ComponentGraphics::Parent,但不能在其签名中使用。在后一种情况下需要类型特征类。