簡體   English   中英

如何使用boost序列化屬性?

[英]How to serialize property using boost?

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>    
struct Foo {
        int  x_, y, z;
        int get_x() const { return x_; }
        void put_x(int v) { x_ = v; }
        __declspec(property(get = get_x, put = put_x)) int x;
        void serialize(auto& ar, unsigned) {
            ar& x; // THIS NOT WORK
            ar& y& z;
        }
    };
    std::ofstream ofs("file.txt");
    boost::archive::binary_oarchive oa(ofs);
    oa << Foo{ 1, 2, 3 };
    std::ifstream ifs("file.txt");
    boost::archive::binary_iarchive ia(ifs);
    Foo foo;
    ia >> foo;

是否可以序列化 __descspec 屬性?

您可以序列化基礎字段。

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

struct S {
    void put_x(int val) { _x = val; }
    int  get_x() const { return _x; }

#ifdef _MSC_VER
   __declspec(property(get = get_x, put = put_x)) int the_prop;
#endif
 private:
   friend class boost::serialization::access;
   template <typename Ar> void serialize(Ar& ar, unsigned) { ar& _x; }
   int _x;
};

int main() {
   std::stringstream ss;
   {
       S s;
#ifdef _MSC_VER
       s.the_prop = 42;
#else
       s.put_x(42);
#endif
       boost::archive::text_oarchive(ss) << s;
   }

   std::cout << "Archive contents: " << ss.str() << "\n";
   {
       S s;
       boost::archive::text_iarchive(ss) >> s;

#ifdef _MSC_VER
       std::cout << "Deserialized: " << s.the_prop << "\n";
#else
       std::cout << "Deserialized: " << s.get_x() << "\n";
#endif
   }
}

印刷

Archive contents: 22 serialization::archive 19 0 0 42

Deserialized: 42

現場觀看 GCC

請參閱在 MSVC 上編譯

更新在 MSVC 上運行

在此處輸入圖像描述

由於 Foo 不會使用 get_x,因此返回 x_ 作為參考。

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>    

struct Foo {
    int  x_, y, z;
    int& get_x() { return x_; }
    void put_x(int v) { x_ = v; }
    __declspec(property(get = get_x, put = put_x)) int x;
    void serialize(auto& ar, unsigned) {
        ar& x; // IT WORKS
        ar& y& z;
    }
};

int main()
{
    {
        std::ofstream ofs("file.txt");
        boost::archive::binary_oarchive oa(ofs);
        oa << Foo{ 1, 2, 3 };
    } {
        std::ifstream ifs("file.txt");
        boost::archive::binary_iarchive ia(ifs);
        Foo foo;
        ia >> foo;
    }
}

暫無
暫無

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

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