C++:实体框架"ash"实现

C++:Implementing "ash" Entity framework

本文关键字:ash 实现 框架 实体 C++      更新时间:2023-10-16

我完全无法尝试将Richard Lord的Ash框架移植到"纯"C++(MSVC Express 2008),或者至少我找不到任何类似的实现,我搞砸了boost:fusion-libs来实现框架所需的最小反射要求,但模板元编程对我来说是全新的,我充斥着编译器错误和耗时的失败测试:(…

有人知道移植该框架的可行性或有用性吗?

以Entity类为例,有人能澄清我如何才能获得这样的结果吗:

(这是FLEX代码!)

    waitEntity = new Entity( "wait" )
            .add( new WaitForStart( waitView ) )
            .add( new Display( waitView ) )
            .add( new Position( 0, 0, 0 ) );

用这样的C++实现?

    ...
    namespace bf = boost::fusion;
    namespace bm = boost::mpl;
    template<typename ComponentMap>
    class EntityASH{
    public:
    EntityASH(ComponentMap c)
    :m_components(c){   }
    //"fusion-style" trying to return a new Components template entity for a new component type
    template<typename T>
    EntityASH
    template<typename T>
/*¿Here im absoltely lost
            EntityASH<
            result_of::as_map<
                    typename result_of::push_back<ComponentMap, 
                    fusion::pair<T,T>
                    >::type
                    >
            >*/
    EntityASH *add(){
            typedef bf::pair<T, T> newTentryPair;
            //bf::as_map(bf::push_back<ComponentMap,newTentryPair>(m_components,newTentryPair()));
            return new EntityASH(bf::as_map(bf::push_back<ComponentMap,newTentryPair>(m_components,newTentryPair())));

C++中的构造函数不能返回一些东西,因此您必须使用另一种方法来创建实体,createEntity()将返回实体对象的引用或std::shared_ptr。

我认为在这里使用模板没有任何好处,因为存储对组件的引用对我来说似乎更正确,因为组件是实体的一部分,不属于实体:

std::shared_ptr<Entity> createEntity() {
    return std::make_shared<Entity>();
}
...
std::shared_ptr<Entity> addComponent(ComponentBase comp) {
    mComponents.add(comp);
    return shared_from_this();
}
...
createEntity().add(new Position())
          .add(new Display())
          .add(new Position());

我不明白你为什么要在这里使用模板?是否希望组件成为实体类型的真实部分?这意味着您无法在运行时以简单的方式添加/删除组件。

我认为在大多数ECS中,实体只是一个容器,出于可用性的原因,它可以完全由一个简单的整数ID代替,但因为这会破坏可用性实体存储对其组件的引用,以便程序员更容易地解决问题。