存储任何值和特定类范围的值

Store any value and a value of a specific range of classes

本文关键字:范围 任何值 存储      更新时间:2023-10-16

我有一个类看起来像这样:

class container{
private:
std::vector<physical_component> physical;
std::vector<storage_component> storage;
--some other stuff not relevant--
public:
--constructors, getters setters, methods to add to the vectors etc--
}

现在我正忙于创建physical_component和storage_components类,因为我不知道处理这类事情的合适数据类型。

Physical_component应该能够:

  1. 存储一定数量的类型,并完全保留一个类型(我可以转换为的类型就足够了)
  2. 应该以使对象与传递的对象独立的方式存储对象(因此可以避免对原始类的更改)

我记得在枚举旁边的c中有这样的兴奋,但我不知道名字。此外,c++可能有更好的方法。

Storage_component应该是:

  1. 存储任何类型
  2. (可选)记住原始类型

我不知道如何正确地实现这一点。我看过std::任何,但它似乎很新,所以我不知道这是否是一个好方法。此外,我不能将storage_component作为模板,因为我不能将其存储在向量中,然后存储在中

实现这些类的(正确的)方法是什么?

存储一定数量的类型,并完全保留一个类型

您可能想要std::variant<Ts...>(或boost::variant<Ts...>)。它在特定时间点存储一个Ts...


存储任何类型的

如果所有类型共享同一接口,请使用传统的virtual+std::unique_ptr多态性方法。否则std::any是正确的选择。