问题
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?
回答1:
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.
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..
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.
回答2:
std::any
does not provide any way of performing an action on the underlying stored type T
. However, information like sizeof(T)
could be available when initializing/assigning to std::any
.
One possible solution is creating your own wrapper around std::any
that keeps track of the size. E.g.
class my_any : std::any
{
std::size_t _stored_size = 0;
public:
template <typename T>
my_any(T&&) : _stored_size{sizeof(std::decay_t<T>)} { }
// ...
};
来源:https://stackoverflow.com/questions/49730735/get-the-size-of-stdany