存储任何值和特定类范围的值
Store any value and a value of a specific range of classes
我有一个类看起来像这样:
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应该能够:
- 存储一定数量的类型,并完全保留一个类型(我可以转换为的类型就足够了)
- 应该以使对象与传递的对象独立的方式存储对象(因此可以避免对原始类的更改)
我记得在枚举旁边的c中有这样的兴奋,但我不知道名字。此外,c++可能有更好的方法。
Storage_component应该是:
- 存储任何类型
- (可选)记住原始类型
我不知道如何正确地实现这一点。我看过std::任何,但它似乎很新,所以我不知道这是否是一个好方法。此外,我不能将storage_component作为模板,因为我不能将其存储在向量中,然后存储在中
实现这些类的(正确的)方法是什么?
存储一定数量的类型,并完全保留一个类型
您可能想要std::variant<Ts...>
(或boost::variant<Ts...>
)。它在特定时间点存储一个Ts...
。
存储任何类型的
如果所有类型共享同一接口,请使用传统的virtual
+std::unique_ptr
多态性方法。否则std::any
是正确的选择。
相关文章:
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- std::map 保存任何值类型
- C++ 矢量未显示我插入的任何值
- 为什么我的变量在我尚未将其设置为任何值时返回一个值?
- 如何将任何值转换为对象并使用 boost::p roperty_tree json 添加成员
- 为什么null std ::可选的被认为小于任何值,而不是更多
- 检查数组中的任何值是否等于添加到数组的当前值
- 如何将任何值转换为字节数组并将其附加到字节列表
- stbi_load不返回任何值
- 带有 std::的任何值unordered_map不能any_cast字符串
- 为什么我的程序一直给我堆缓冲区溢出,即使我没有超出数组的界限或覆盖任何值
- 如何使用difference_type按任何值增加/减少reverse_iterator
- 为什么在C 中不确定,为签名类型的对象分配范围的值的结果
- c++:何时初始化声明的变量而不将其分配给任何值
- 存储任何值和特定类范围的值
- 如何使用 std:fill 为 C 数组的特定范围设置值
- mpi_scatterv不将任何值返回到recvbuf
- getline 没有为字符串对象分配任何值
- 如何为任何值编码欧拉 #3
- CORBA::String_var -> 我无法为这种类型的类字段分配任何值