我在为push_back
的{{1}}创建std::vector
函数时遇到问题。到目前为止,这是我的结构的最小实现:
std::variants
现在假设我想添加一个template<class T, class Ts...> //Must construct with at least 1 argument
struct entity_container
{
entity_container(T arg1, Ts ...args) //constructor, populate vector of std::variant's
{
entities.push_back(std::forward<decltype(arg1)>(arg1));
auto loop = [&](auto&& arg)
{
entities.push_back(std::forward<decltype(arg)>(arg));
}
(loop(args),...);
}
std::vector<std::variant<T, Ts...>> entities;
}
函数,那么我考虑了一些事情:
如果我们要添加push_back
的{{1}}中已经存在的类型,那么我们可以简单地使用:std::variant
如果我们要向entity_container::entities
添加 new 类型,则需要扩展entities.push_back(entity)
的类型,然后创建一个新的entity_container::entities
并把所有元素从旧向量移到新向量。
在第二种情况下,我遇到了两篇文章:
extending a variant type in c++和 copy/move elements between two std::variants
因此,我想要使用这些工具来实现我的std::variant
实现:
std::vector
但这有很多很多问题。
我们如何检查类型push_back
是该变体的新类型?
template<typename E>
void push_back(E&& entity)
{
if( /* E is a new type to the variant */)
{
//std::variant<Old..., New> = std::variant<Old...> + New
using extended_type = t_variant_cat_t<std::remove_reference_t<decltype(Entities[0])>,
std::remove_reference_t<E>>;
//construct (with the new element) a new entity_container with the extended type,
entity_container<extended_type> entities_new(entity);
//move the entities from the old container to the new one
for(auto& ent : Entities)
entities_new.entities.push_back(std::move(ent)); //all entities are moveable types
//update replace the old container with the new
entities = entities_new;
}
else /* E is not a new type to the variant */
{
entities.push_back(entity);
}
}
类似于E
,但实际上我们必须将extended_type
构造为std::variant<T1, T2, T3, T4>
-如何从{ {1}}到类型包?
当我们最后进行entity_container
时,这两个对象具有不同的类型,因此无法彼此分配(即使(2)可以固定)
最后,我们必须每次重构容器 ,将元素推回。那真的会很慢。
所以我的总体问题是,是否有人有解决上述问题的想法,或者是编写此功能的全新方法。
请注意,结构按如下方式使用:
entity_container<T1, T2, T3, T4>