How to convert tuple to byte array in c++11

被刻印的时光 ゝ 提交于 2019-12-19 10:00:45

问题


I need to write a function to convert tuple to byte array. The type of tuple may include int, long, double, std::string, char*,etc. The size and type of tuple are arbitrary, such as

std:tuple<string, int, double> t1("abc", 1, 1.3);

or

std:tuple<char*, int, int, float, double, string> t2("abc", 1, 2, 1.3, 1.4, "hello");

I want use these tuple as input, and the byte array as return value. What should I do ?


回答1:


There is also the brilliant C++ API for message pack which supports tuples natively

#include <string>
#include <sstream>
#include <tuple>

#include <msgpack.hpp>

int main() {
    auto t = std::make_tuple("1", 1, 1.0);
    auto buffer = std::stringstream{};

    // easy peezy
    msgpack::pack(buffer, t);
    auto tuple_as_string = buffer.str();
}



回答2:


You can use Boost Serialization for this task together with a small extension for std::tuple. However, it doesn't turn it into a byte array by default, but into something else. There is also binary_oarchive. Perhaps this fits your needs.

#include <fstream>
#include <tuple>

#include <boost/archive/text_oarchive.hpp>

#include "serialize_tuple.h" // https://github.com/Sydius/serialize-tuple

int main()
{
  auto t = std::make_tuple(42,3.14,'a');

  std::ofstream ofs("test.dat");
  boost::archive::text_oarchive oa(ofs);
  oa << t;
}


来源:https://stackoverflow.com/questions/44793303/how-to-convert-tuple-to-byte-array-in-c11

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