使用boost序列化的Microsoft GUID序列化?

时间:2017-09-10 10:35:25

标签: c++ serialization boost guid

我有以下内容:

struct Member
{
    GUID id;
    int extra;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int file_version)
    {
        ar & id;
        ar & extra;
    }

}

当我编译代码时,我得到以下编译错误:

错误25错误C2039:&#39;序列化&#39; :不是&#39; _GUID&#39;

的成员

如何专门为Microsoft GUID提升序列化?

1 个答案:

答案 0 :(得分:2)

这是一个提示:假设UUID类型是POD,您可以使用make_binary_object

这是UUID作为POD的模型类型:

#include <array>

using UUID = std::array<uint8_t, 16>; // mock up
static_assert(std::is_pod<UUID>(), "assumes UUID is POD");

任何POD都可以。例如。 boost::uuids::uuid¹也是POD。 struct UUID { char data[16]; }等。

相同

非侵入式序列化:

#include <boost/serialization/serialization.hpp>
#include <boost/serialization/binary_object.hpp>

namespace boost { namespace serialization {
    template <typename Ar>
        void serialize(Ar& ar, UUID& u, unsigned /*version*/) {
            ar & make_binary_object(&u, sizeof(u));
        }
} }

演示

<强> Live On Coliru

#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

int main() {
    std::stringstream ss;
    {
        boost::archive::text_oarchive oa(ss);
        UUID u {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}};
        oa << u;
    }

    std::cout << ss.str() << "\n";

    {
        boost::archive::text_iarchive ia(ss);
        UUID u {};
        ia >> u;

        std::copy(begin(u), end(u), std::ostream_iterator<int>(std::cout << "roundtripped: ", " "));
    }
}

¹虽然该库已经在boost/uuid/uuid_serialize.hpp标题

中定义了序列化