Get the size of std::any

允我心安 提交于 2020-05-27 10:47:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!