我正在std::vector
中存储std::tuple
s的集合。但是,当我从元组中获取一个元素并对其进行修改时,我只修改了返回元素的副本。
template<typename... Ts>
class ComponentStore
{
public:
ComponentStore()
{
}
~ComponentStore()
{
}
template<typename T>
std::vector<T>& Get()
{
return std::get<std::vector<T>>(m_components);
}
private:
std::tuple<std::vector<Ts>...> m_components;
};
这就是我计划使用ComponentStore
类:
ecs::component::ComponentStore<ecs::component::Position, ecs::component::Velocity> comstore;
//Get the position vector
auto positionvec = comstore.Get<ecs::component::Position>();
//Add a new position
positionvec.emplace_back(ecs::component::Position{});
//Later on, get the position vector again
auto positionvec2 = comstore.Get<ecs::component::Position>();
//But it's empty??? this is wrong. It should have 1 element.
答案 0 :(得分:4)
通过单独使用auto,您可以创建推导出的非引用类型的变量,所以
auto positionvec = comstore.Get<ecs::component::Position>();
创建一个新的向量;
您可以使用auto&amp;:
解决此问题auto& positionvec = comstore.Get<ecs::component::Position>();