gpt4 book ai didi

c++ - 创建一个容器来存储模板类实例

转载 作者:行者123 更新时间:2023-12-02 09:47:46 26 4
gpt4 key购买 nike

假设我有一个模板结构:

template<typename T>
struct Entity
{
Entity(int Id) : id(Id)
{
/* init 'data' */
}

T* data;
int id;
};
第二类角色是存储各种类型的实体:
typename<Ts...>
class EntityContainer
{
public:
EntityContainer(Ts... Args)
{
/* store 'Args' (which are all template instantiations of entity) in some 'entity container' */
}

template<typename T>
void addNewEntity(T&& entity)
{
/* new entities can be added to the 'entity container' at run time */
}

template<typename T>
T& getEntityById(int id)
{
/* stored Entities must be accessible and mutable at run time */
}
private:
/*Entity container goes here e.g. std::tuple<Ts...> */
};
这两个类将串联使用,如下所示:
//create two entities of differing types
Entity<A> myFirstEntity(1);
Entity<B> mySecondEntity(2);

//store the entities in a container
EntityContainer<Entity<A>, Entity<B>> myContainer(myFirstEntity, mySecondEntity);

//create a new Entity and add it to the container
Entity<C> myThirdEntity(3);
mycontainer.addNewEntity(myThirdEntity);

//retrieve entity from container at run time
myContainer<Entity<B>>.getEntityById(2); //should return 'mySecondEntity'
因此,我已经尝试了一段时间,并且在 std::tuple类中使用 EntityContainer作为实体容器非常接近,但是问题是我在运行时无法访问和更改 std::tuple中的特定元素时间,所以我认为这不适合这份工作。也许这根本不是正确的方法,而基于继承的解决方案更合适,但我想不出一个。
我试图在提供足够的代码的同时尽可能地使这一点变得清晰,我希望这不会问得太多,只是在寻找一些方向。

最佳答案

inheritance based solution would be more apt, but I cant think of one.


使 Entity为常规类的子类,并存储指向基类的指针。
struct EntityBase
{
virtual ~EntityBase() {}
};

template<typename T>
struct Entity : EntityBase
{
...
};

现在, EntityContainer可以存储指向 EntityBase的指针,最好是智能指针。

关于c++ - 创建一个容器来存储模板类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63961106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com