msgpack-c icon indicating copy to clipboard operation
msgpack-c copied to clipboard

MSGPACK_DEFINE and inheritance

Open purplesyringa opened this issue 5 years ago • 11 comments

Consider the following example:

class A {
    int a;
    MSGPACK_DEFINE_MAP(a);
};

class B: public A {
    int b;
    MSGPACK_DEFINE_MAP(b);
};

MSGPACK_DEFINE_MAP(b) in derived class overrides base class definition. Is it possible to make it work as MSGPACK_DEFINE_MAP(a, b) instead?

purplesyringa avatar Mar 22 '20 08:03 purplesyringa

You need to use MSGPACK_BASE to serialize base classes See https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor#intrusive-approach

redboltz avatar Mar 22 '20 10:03 redboltz

Oh, sorry, I didn't notice this. Closing this then.

purplesyringa avatar Mar 22 '20 12:03 purplesyringa

Hm, actually, this doesn't answer my question. I need to get {"a": a, "b": b} but I get {"A": {"a": a}, "b": b} with MSGPACK_BASE_MAP.

purplesyringa avatar Mar 22 '20 13:03 purplesyringa

You can do as follows: https://wandbox.org/permlink/TUkoxgGmGiatHPau

redboltz avatar Mar 22 '20 13:03 redboltz

True, but in reality A has a lot more fields and it has several derived classes, so copying the same list to all derived classes is not an option.

purplesyringa avatar Mar 22 '20 13:03 purplesyringa

Ok, you can't do that. I think that MSGPACK_BASE is better choice.

redboltz avatar Mar 22 '20 13:03 redboltz

Do you mean that I have to use {"A": {"a": a}, "b": b} instead? Unfortunately I'm not making an app from scratch but following an existing specification so I can't do that.

purplesyringa avatar Mar 22 '20 13:03 purplesyringa

Do you mean that I have to use {"A": {"a": a}, "b": b} instead?

Yes. Unfortunately msgpack-c doesn't support your case.

redboltz avatar Mar 22 '20 13:03 redboltz

Perhaps you can write your adaptor using non-intrusive approach. But I'm not sure. See https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor#non-intrusive-approach

redboltz avatar Mar 22 '20 13:03 redboltz

Is it possible to allow specifying a meta-value (e.g. MSGPACK_EMBED) as a key to insert other class contents?

purplesyringa avatar Mar 22 '20 14:03 purplesyringa

Is it possible to allow specifying a meta-value (e.g. MSGPACK_EMBED) as a key to insert other class contents?

My first impression, it is not possible.

BTW, directly adding base class member is bad idea in general. See https://github.com/msgpack/msgpack-c/issues/74#issuecomment-89976652

You need to write your custom adaptor. I'm not sure it is possible. If it is not possible, you can write some filter converting {"a": a, "b": b} from/to {"A": {"a": a}, "b": b} to support your special requiement.

redboltz avatar Mar 22 '20 14:03 redboltz