C++ msgpack User-defined classes - can't get started

瘦欲@ 提交于 2019-12-11 08:02:37

问题


I've been looking at the C++ quick-start guide for msgpack.

http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387

There, there is the following code snippet:

#include <msgpack.hpp>
#include <vector>
#include <string>

class myclass {
private:
    std::string str1;
    std::string str2;
public:
    MSGPACK_DEFINE(str1,str2);
};

int main(void) {
        std::vector<myclass> vec;
        // add some elements into vec...
        /////
        /* But what goes here??? */
        /////

        // you can serialize myclass directly
        msgpack::sbuffer sbuf;
        msgpack::pack(sbuf, vec);

        msgpack::unpacked msg;
        msgpack::unpack(&msg, sbuf.data(), sbuf.size());

        msgpack::object obj = msg.get();

        // you can convert object to myclass directly
        std::vector<myclass> rvec;
        obj.convert(&rvec);
}

I want to serialize a vector of myclass objects.

I've tried the following:

...
vector<myclass> rb;
myclass mc;

...

int main(){
    ...
    mc("hello","world");
    rb.push_back(mc)
    ...
}

But this doesn't work ("error: no match for call")

also, if I do:

mc.str1="hello"
mc.str2="world"

it won't work as str1 and str2 are private.

How to use this MSGPACK_DEFINE(...) macro properly? I can't seem to find anything online.

Many thanks,


回答1:


MSGPACK_DEFINE() defines some methods implementing packing and unpacking for your class. What you put inside () is a list of the members you want serialized.

After that, you can pack and unpack your class just like you would pack or unpack an int. So the example should be working.

You can try removing the vector and pack only a single object - I think that would simplify it.




回答2:


class myclass {
    private:
        std::string str1;
        std::string str2;
    public:
        myclass(){};
        myclass(string s1,string s2):str1(s1),str2(s2){};
        MSGPACK_DEFINE(str1,str2);
};

int main(int argc, char **argv)
{
    std::vector<myclass> vec;
    myclass m1("m1","m2");
    vec.push_back(m1);

    // you can serialize myclass directly
    msgpack::sbuffer sbuf;
    msgpack::pack(sbuf, vec);

    msgpack::unpacked msg;
    msgpack::unpack(&msg, sbuf.data(), sbuf.size());

    msgpack::object obj = msg.get();

    // you can convert object to myclass directly
    std::vector<myclass> rvec;
    obj.convert(&rvec);
}


来源:https://stackoverflow.com/questions/9326862/c-msgpack-user-defined-classes-cant-get-started

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!