Search code examples
c++msgpack

How to pack string in C++ msgpack?


msgpack::object elem;
std::string tempString = "string";
elem["type"] = msgpack::pack(tempString);

Above code doesn't work

error: no matching function for call to 'pack(std::string&)'

How can I pack string into msgpack::object?


Solution

  • msgpack::pack() is a free function template in the namespace msgpack:

    template <typename Stream, typename T>
    inline void pack(Stream& s, const T& v);
    

    The function obviously is stateless and needs a target where to pack the tempString to. The target can be any class that has the member funciton write(const char*, std::size_t);. For example, use std::stringstream:

    std::string tempString = "string";
    std::stringstream messagePacked;
    msgpack::pack(messagePacked, tempString);
    

    And you might want this:

    msgpack::object elem;
    std::string tempString = "string";
    elem["type"] = tempString;
    std::stringstream messagePacked;
    msgpack::pack(messagePacked, elem);