C ++ - boost ::任何序列化 [英] C++ - boost::any serialization

查看:283
本文介绍了C ++ - boost ::任何序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,没有序列化( boost :: serialization ,实际上)支持 boost :: any 占位符。

As far as I understand, there is no serialization (boost::serialization, actually) support for boost::any placeholder.

有人知道是否有一种方法可以序列化自定义 boost :: any 实体?

Does someone know if there is a way to serialize a custom boost::any entity?

这里的问题很明显: boost :: any 使用基于模板的占位符存储对象, typeid 以检查 boost :: any_cast 是否合适。

The problem here is obvious: boost::any uses template-based placeholders to store objects and typeid to check if boost::any_cast is appropriate.

因此,有一个定制的抽象超类占位符和基于定制模板的派生类,它们是通过以下方式创建的:

So, there is a custom abstract superclass placeholder and custom template-based derived classes, which are created the following way:

template <T> custom_placeholder : public placeholder {
    virtual std::type_info type() const { return typeid(T); }
    virtual ...
};

显然,这会带来一些麻烦,甚至考虑序列化这些东西。

谢谢

推荐答案

这是不可能的,至少对于任意类型。注意,也许你可以使用一些棘手的代码(比如找到包含在任何的元素的大小)序列化,但任何代码依赖于编译器静态放置任何type_code和正确的类型占位符。你肯定不能在C ++中反序列化,因为你从反序列化中得到的类型在编译时是未知的(如新形成的 boost :: any )。

It is not possible at all, at least for arbitrary types. Note that maybe you could serialize using some tricky code (like finding the size of the elements contained in the any), but the any code relies on the compiler statically putting the any type_code and the proper types inside the placeholder. You surely cannot do that in deserialization in C++, as the type that you'd get from the deserialization is not known at compile time (as required by the newly formed boost::any).

最好的解决方案是为你要序列化的元素的精确类型构建某种专门的任何类型。然后,你可以有被反序列化的元素的实际类型的特殊情况,但是注意每个元素类型序列化/反序列化必须以静态C ++代码的形式写。

The best solution is to build some kind of specialized any type for the exact types of elements you're going to serialize. Then, you can have special cases for the actual type of element being deserialized, but note that each element type serialization/deserialization has to be phisically written as static C++ code.

PD。一些其他人建议使用 boost :: variant 作为这种专门类型的表示,保存要序列化的确切类型。你需要一种方法来辨别反序列化的确切类型,尽管(可能为变量中的类型指定标识符)。

PD. Some others suggested using boost::variant as a representation of this specialized type holding the exact types you're going to serialize. You need a way of discerning the exact type on deserialization, though (maybe assigning identifiers to types in the variant).

这篇关于C ++ - boost ::任何序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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