C ++:升压提取物大小::变种元素 [英] C++: Extract size of boost::variant element

查看:142
本文介绍了C ++:升压提取物大小::变种元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个载体,其中包含它的boost ::变量元素结构。

I have a vector, which contains structs with boost::variant elements in it.

现在我有序列化这个载体。因为规范的我都数不过来了八位位组,这是需要保存这个矢量。现在,我在寻找一个简单的方法来实现这个选项。

Now i have to serialize this vector. Because of the specification i have to count the octets, which are needed to save this vector. Now I'm searching for a option to realize this in a easy way.

int allSize = 0;

for(auto it=vec.begin(); it != vec.end(); it++){
    //something like size = sizeof(it->variant)
    allsize += size;
}

我就先用

sizeof(it->variant.type())

,但这仅示出了变体元件的尺寸(这是最大的元件从德变体保持的大小)

but this shows only the size of the variant element (which is the size of the biggest element held from te variant)

那么,有没有一种简单的方法来获得序列化的数据的大小?
或者我必须写一个游客约7模板?

So, is there an easy way to get the size of the serialized data? Or do i have to write a visitor with about 7 templates?

推荐答案

您可以做到这一点的游客,类似如下:

You can do that in the visitor, something like following :

/*
template <typename T>
using EnableIf = typename std::enable_if< std::is_pod<T>::value >::type* ;
*/

struct visit: public boost::static_visitor<>
{
    visit(  ): size(0) { }
    template<typename T /*, EnableIf<T> = nullptr */  >
    void operator()(  T& x) const
    {
        size += sizeof ( x ) ;
        //std::cout <<  sizeof ( x ) << ":" << x << '\n';
    }

    std::size_t get_size() const
    { return size ; }
    private:
        mutable std::size_t size ;

};

然后,

visit visito ;
std::for_each( vec.begin(), vec.end(), 
               boost::apply_visitor( visito) );

std::cout << visito.get_size() ;

修改:删除评论检查POD数据Type仅通过注释<一个href=\"http://stackoverflow.com/questions/27012488/c-extract-size-of-boostvariant-element/27012996#comment42552279_27012996\">sehe,因为保存非POD所需的字节数量的可能的并不总是等于的sizeof(T)

Edit: Remove comment to check for POD data type only as commented by sehe, since amount of bytes needed to save a non-pod might not always be equal to sizeof(T)

这篇关于C ++:升压提取物大小::变种元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆