问题描述
是否有任何方法可以获取std::any
存储的数据大小(以字节为单位)?我想出的唯一解决方法是通过std::any::type
查询其值的类型,然后将结果与已知类型的列表(例如my_any.type() == typeid(T)
)进行比较,然后将大小设置为sizeof(T)
.不幸的是,这种解决方案仅在事先知道类型的情况下才有效.
Is there any way to get the size (in bytes) of the data stored by std::any
? The only workaround I came up with is querying the type of its value by std::any::type
and comparing the result to a list of known types like my_any.type() == typeid(T)
, then the size is sizeof(T)
. Unfortunately, this solution only works when the types are known beforehand.
你知道什么解决办法吗?
Do you know any solution?
推荐答案
您无法获取std::any
持有的对象的大小(您提到的解决方法除外). std::any
是类型擦除的 minimum 实现.
You cannot get the size of the object held by std::any
(other than the workaround you've mentioned). std::any
is a minimal implementation of type erasure.
如果您想要更强大的功能,请自己编写(这并不难,只需在std::any
或boost::any
上建模并添加size()
功能).您可能还需要添加许多其他内容,例如I/O,将多个数据(或任何容器的内容)存储为数组等.
If you want something more powerful, write it yourself (it's not hard, just model it on std::any
or boost::any
and add the size()
functionality).There are many other things you may want to add to any
, such as I/O, storing multiple data (or the contents of any container) as arrays, etc..
如Vittorio的.
At the expense of an additional data member (to store the size), you may also extend std::any
by writing a wrapper, as suggested in Vittorio's answer.
这篇关于获取std :: any的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!