개체를 직렬화 및 역 직렬화하는 일련의 템플릿 함수를 작성하고 싶습니다. 직렬화 부분을 완료했으며 모든 것이 작동합니다.
#ifndef SERIALIZE_H
#define SERIALIZE_H
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <memory>
inline std::string to_json(int value) {
return std::to_string(value);
}
inline std::string to_json(long value) {
return std::to_string(value);
}
inline std::string to_json(double value) {
return std::to_string(value);
}
inline std::string to_json(const std::string& myStr) {
return "\"" + myStr + "\"";
}
template <typename T>
std::string to_json(const std::vector<T>& vec) {
std::string json("[");
for(auto &i : vec) {
json += to_json(i);
json += ",";
}
if (!vec.empty()) json.pop_back();
json += "]";
return json;
}
template <typename T>
std::string to_json(const std::unordered_set<T>& mySet) {
std::string json("[");
for(const auto& i : mySet) {
json += to_json(i);
json += ",";
}
if (!mySet.empty()) json.pop_back();
json += "]";
return json;
}
template <typename K, typename V>
std::string to_json(const std::unordered_map<K, V>& myMap) {
std::string json("{");
for(const auto& i : myMap) {
json += to_json(i.first);
json += ":";
json += to_json(i.second);
json += ",";
}
if (!myMap.empty()) json.pop_back();
json += "}";
return json;
}
#endif //SERIALIZE_H
이것은 serialize.h
모든 종류의 조합을 직렬화 할 수 있습니다 unordered_map<string, vector<int>>
.
이제 임의의 조합을 지원하기 위해 역 직렬화 기능을 재귀 적으로 구현하는 방법을 모르겠습니다.
다음은 deserialize.h
작동하지 않는 내 입니다.
#ifndef DESERIALIZE_H
#define DESERIALIZE_H
#include <string>
#include <rapidjson/document.h>
template<typename T>
T from_json(const std::string &json);
template<>
int from_json(const std::string &json) {
return std::stoi(json);
}
template<>
long from_json(const std::string &json) {
return std::stol(json);
}
template<>
double from_json(const std::string &json) {
return std::stod(json);
}
template<>
std::string from_json(const std::string &json) {
return json.substr(1, json.size()-1);
}
//
template<typename T>
std::vector<T> from_json(const std::string& json) {
rapidjson::Value jsonValue;
{
const std::string &input = "{\"input\":" + json + "}";
rapidjson::Document document;
document.Parse(input.c_str());
jsonValue = document["input"];
};
std::vector<T> vec;
assert(jsonValue.IsArray());
for (rapidjson::SizeType i = 0; i < jsonValue.Size(); i++) {
int element = from_json<T>(std::string(jsonValue[i].GetString()));
vec.push_back(element);
}
return vec;
}
#endif //DESERIALIZE_H
rapidjson
C ++ JSON 라이브러리, https://github.com/miloyip/rapidjson
그런 다음 JSON 문자열을 역 직렬화하려고하면 :
#include "deserialize.h>
int main() {
auto vec1 = from_json<std::vector<int>>(std::string("[1,2,3]"));
return 0;
}
컴파일 오류가 발생합니다.
error: call of overloaded ‘from_json(std::string)’ is ambiguous
직렬화만큼 쉽게 역 직렬화 기능을 구현할 방법이없는 것 같습니다.
어떤 아이디어?
매번 동일한 인수와 다른 반환 유형을 사용하여 동일한 함수 (from_json (...))를 오버로드하려고합니다. 이것은 합법적이지 않습니다. 오버로딩의 경우 다른 인수 유형 또는 인수 번호가 필요합니다.
Instead of
template<>
double from_json(const std::string &json) {
return std::stod(json);
}
template<>
std::string from_json(const std::string &json) {
return json.substr(1, json.size()-1);
}
아마도 이것을 시도하거나 적어도 이것은 일반적인 아이디어 여야합니다.
template<>
void from_json(const std::string &json, double *out_value) {
*out_value = std::stod(json);
}
template<>
void from_json(const std::string &json, std::string *out_value) {
out_value = json.substr(1, json.size()-1);
}
오류가 있다고 확신하지만 이렇게하면 작동 할 수 있다고 생각합니다 (수정하면).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다