0

Using C++14 I want to define optional parameters for msgpack.

Right now I have something like this: MSGPACK_DEFINE(varA, varB, varC);, where each of these variables is optional and changes with the specific type I am trying to pack. For example, one type of object will need varA and varC, but not varB.

Is there a clean way to do this all in one class?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Makoto
  • 1,520
  • 2
  • 12
  • 19

1 Answers1

0

@kennytm 's comment pointed to the answer.

I answer the complete working code example based on your case. MSGPACK_DEFINE_MAP provides map based serialization. So you can choose any member variables that you want to adapt.

#include <iostream>
#include <sstream>
#include <msgpack.hpp>

struct S1 {
    int varA;
    int varB;
    int varC;
    MSGPACK_DEFINE_MAP(varA, varB, varC);
};

struct S2 {
    int varA;
    int varC;
    MSGPACK_DEFINE_MAP(varA, varC);
};


int main() {
    S1 s1 { 1, 2, 3};
    std::stringstream ss;
    msgpack::pack(ss, s1);
    auto oh = msgpack::unpack(ss.str().data(), ss.str().size());
    auto s2 = oh.get().as<S2>();
    std::cout << s2.varA << "," << s2.varC << std::endl;
}

You can also run the code above the following online compiler: http://melpon.org/wandbox/permlink/NbaSjMPdtdwqBp7m

Takatoshi Kondo
  • 3,111
  • 17
  • 36