簡體   English   中英

如何使用谷物序列化boost :: uuid

[英]How to serialize a boost::uuid with cereal

試圖序列化這個簡單的類:

class Data
{
public:
    Data();
    Data(boost::uuids::uuid id);

    Data(const Data&) = delete;
    Data& operator=(const Data&) = delete;

    inline boost::uuids::uuid getGuid() { return guid; }

    template <class Archive>
    void serialize(Archive & ar)
    {
        ar(guid);
    }

private:
    boost::uuids::uuid guid;
};

但我收到此錯誤消息

error C2338: Trying to serialize an unserializable type with an output archive. 

Poiting到uuid。 啟用此功能的boost序列化方法是添加

#include <boost/uuid/uuid_serialize.hpp>

但這不適用於谷物開箱即用。 谷歌文件說

谷物檔案可以在std :: ostream或std :: istream對象上運行。

所以我嘗試添加標題,但沒有運氣

#include <boost/uuid/uuid_io.hpp>

這適用於谷物JSON檔案。 我還在評論中包含了為二進制存檔執行此操作的方法。

#ifndef CEREAL_TYPES_BOOST_UUID_
#define CEREAL_TYPES_BOOST_UUID_

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>

namespace cereal
{
    template <class Archive> inline
        void save(Archive& ar, boost::uuids::uuid const& uuid)
    {
        std::string val = boost::lexical_cast<std::string>(uuid);

        ar(val);

        // Other approach, probably better for binary
        //ar(make_size_tag(static_cast<size_type>(uuid.size())));
        //for (auto it = uuid.begin(), end = uuid.end(); it != end; ++it)
        //  ar(*it);
    }

    template <class Archive> inline
        void load(Archive& ar, boost::uuids::uuid& uuid)
    {
        std::string val;

        ar(val);
        uuid = boost::lexical_cast<boost::uuids::uuid>(val);

        // Other approach, probably better for binary
        //size_type size;
        //ar(make_size_tag(size));

        //for (auto it = uuid.begin(), end = uuid.end(); it != end; ++it) {
        //  uint8_t val;
        //  ar(val);
        //  *it = val;
        //}
    }
} // namespace cereal

#endif // CEREAL_TYPES_BOOST_UUID_

這個事實

谷物檔案可以在std :: ostream或std :: istream對象上運行。

(根本沒有)暗示它使用IO流操作符(>>,<<)。 這只是存檔實現。

你必須實現自由函數serialize ,讓谷歌知道你的類型。 您應該能夠重用uuid_serialize.hpp顯示的實現。 你應該很簡單

  • 將這些定義移到谷物命名空間(最好)或升級到boost :: uuids命名空間(將來可能會發生沖突),以便ADL找到它們
  • 最好將UUID視為簡單的字節數組(AFAIR boost::uuids::uuid是POD數據類型)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM