请参阅下面的代码:(您可以使用以下命令编译代码:g++-4.7 demo.cpp -std=c++11 -lmsgpack)
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <msgpack.hpp>
using namespace std;
template<class T>
void pack(T &t, string &str)
{
using namespace msgpack;
sbuffer buff;
pack(buff, t);
ostringstream is;
is << buff.size() << buff.data();
str = string(is.str());
}
template<class T>
T unpack(string &str)
{
using namespace msgpack;
unpacked result;
istringstream ss(str);
int len;
string buff;
ss >> len >> buff;
unpack(&result, buff.c_str(), len);
auto obj = result.get();
return obj.as<T>();
}
int main(int argc, char *argv[]) {
vector<float> t = {1., 2., 3., 4., 5.};
string s;
pack(t, s);
auto r = unpack<vector<float> >(s);
for(auto & v : r)
std::cout << v << std::endl;
// vector<int> is right
/*
vector<int> t = {1, 2, 3, 4, 5};
string s;
pack(t, s);
auto r = unpack<vector<int> >(s);
for(auto & v : r)
std::cout << v << std::endl;
*/
return 0;
}
有一个奇怪的bug,'vector','vector','int','double'可以在上面的封装中工作,而'vector','vector'不能。
运行时错误显示如下:
terminate called after throwing an instance of 'msgpack::type_error'
what(): std::bad_cast
但在下面的封装中,任何类型都可以正常工作:
template<class T>
void pack(T &t, msgpack::sbuffer sbuf) {
pack(&sbuf, t);
}
template<class T>
T unpack(const msgpack::sbuffer & sbuf) {
msgpack::unpacked msg;
msgpack::unpack(&msg, sbuf.data(), sbuf.size());
auto obj = msg.get();
return obj.as<t>();
}
我的第一个代码有什么问题?谢谢!