如何使用Cereal库将枚举的数组/向量序列化为XML?

时间:2019-06-29 16:08:13

标签: c++ serialization xml-serialization cereal

我试图将枚举向量序列化为整数值,而不是整数值。通过启用save-load和/或save_minimal-load_minimal,会生成编译错误。我只对序列化感兴趣。反序列化功能只是为了避免最终的错误。

include <fstream>
#include <cereal/types/vector.hpp>
#include <cereal/archives/xml.hpp>

namespace Test
{
    enum Enum
    {
        alpha,
        beta,
        gamma
    };

    static const char* const text[]
    {
        "alpha",
        "beta",
        "gamma"
    };

    typedef std::vector<Enum> EnumVector;

    class Object
    {
    public:
        typedef std::vector<Object> Vector;

        EnumVector data;

        template <class Archive>
        void save(Archive& archive) const
        {
            archive(cereal::make_nvp("data", data));
        }

        template <class Archive>
        void load(Archive& archive)
        {
            archive(cereal::make_nvp("data", data));
        }
    };

#if 0
    template <class Archive>
    void save(Archive& archive, const Enum item)
    {
        const std::string t = text[item];
        archive(t);
    }

    template <class Archive>
    void load(Archive& archive, Enum& item)
    {
        std::string value;
        archive(value);

        int i = 0;
        for(; i != 3; ++i)
        {
            if (value == text[i])
            {
                break;
            }
        }

        item = Enum(i);
    }
#endif
}

#if 0
namespace cereal
{
    template <class Archive>
    std::string save_minimal(Archive&, const ::Test::Enum item)
    {
        return ::Test::text(item);
    }

    template <class Archive>
    void load_minimal(const Archive&, ::Test::Enum& item, const std::string& value)
    { 
        int i = 0;
        for(; i != 3; ++i)
        {
            if (value == ::Test::text[i])
            {
                break;
            }
        }

        item = ::Test::Enum(i);
    }
}
#endif

int main()
{
    using namespace Test;
    Object::Vector objects{ {{alpha, alpha, gamma}}, {{beta, gamma, gamma}}};

    std::ofstream ofs("out.xml");
    cereal::XMLOutputArchive out(ofs);
    out(cereal::make_nvp("objects", objects));
}

预期输出应为

<?xml version="1.0" encoding="utf-8"?>
<cereal>
    <objects size="dynamic">
        <value0>
            <data size="dynamic">
                <value0>alpha</value0>
                <value1>alpha</value1>
                <value2>gamma</value2>
            </data>
        </value0>
        <value1>
            <data size="dynamic">
                <value0>beta</value0>
                <value1>beta</value1>
                <value2>gamma</value2>
            </data>
        </value1>
    </objects>
</cereal>

PS对于XML,向量/数组项的命名很奇怪,因为很难为这种表示法定义XML模式(XSD)。可以抑制数字吗?

0 个答案:

没有答案