msgpack / msgpack-c

MessagePack implementation for C and C++ / msgpack.org[C/C++]
Other
3.03k stars 883 forks source link

Single function to pack multiple classes #1009

Open dlandtaa opened 2 years ago

dlandtaa commented 2 years ago

I would like to have a base class that handles the creation of the messagepack so that all the derived classes can use it.

class BaseClass
{
public:
    msgpack::sbuffer Pack()
    {
        msgpack::sbuffer buff;
        msgpack::pack(buff, *this);
        return buff;
    }
};

class DerivedClass: public BaseClass
{
public:
    MSGPACK_DEFINE_MAP(message);

private:
    std::string message;
};

That way I can do

DerivedClass d;
d.Pack();

I will have several classes all deriving from BaseClass so it would be best to have Pack() in that class. However, when I attempt to do this I get this error:

error: no member named 'msgpack_pack' in 'BaseClass'

Is it possible to put just the call to msgpack::pack in a single function that all the types can use?

redboltz commented 2 years ago

It is not possible. You need to implementt your custom paking logic using virtual function mechanism by yourself.