프로그래밍/C,C++
[RapidJson] 가변 파라미터 함수로 json 값 추가하기
MAKGA
2023. 5. 8. 22:48
320x100
// rapidjson/writer.h
template<typename T>
void WriteJsonValue(const char* key, T value);
// WriteJsonValue for const char* values
template<>
void WriteJsonValue(const char* key, const char* value)
{
Key(key);
String(value);
}
// WriteJsonValue for bool values
template<>
void WriteJsonValue(const char* key, bool value) {
Key(key);
Bool(value);
}
// WriteJsonValue for integral types
template<>
void WriteJsonValue(const char* key, char value)
{
Key(key);
Int(value);
}
template<>
void WriteJsonValue(const char* key, unsigned char value)
{
Key(key);
Uint(value);
}
template<>
void WriteJsonValue(const char* key, short value)
{
Key(key);
Int(value);
}
template<>
void WriteJsonValue(const char* key, unsigned short value)
{
Key(key);
Uint(value);
}
template<>
void WriteJsonValue(const char* key, int value)
{
Key(key);
Int(value);
}
template<>
void WriteJsonValue(const char* key, unsigned int value)
{
Key(key);
Uint(value);
}
template<>
void WriteJsonValue(const char* key, __int64 value)
{
Key(key);
Int64(value);
}
template<>
void WriteJsonValue(const char* key, unsigned __int64 value)
{
Key(key);
Uint64(value);
}
template<>
void WriteJsonValue(const char* key, float value)
{
Key(key);
Double(value);
}
// WriteJsonObject function declaration
template<typename... Args>
void WriteJsonObject(Args... args);
// WriteJsonObject variadic template function
template<typename T, typename... Args>
void WriteJsonObject(const char* key, T value, Args... args)
{
WriteJsonValue(key, std::forward<T>(value));
WriteJsonObject(std::forward<Args>(args)...);
}
void WriteJsonObject() {}
// 사용 예시
// example.cpp
rapidjson::StringBuffer sb;
rapidjson::Writer writer(sb);
writer.WriteJsonObject("key", value, "key2", "value");
여기서 좀 더 개선한다면 int64, unsigned int64 타입을 제외하곤 정수형 타입 특화 함수로 통일해도 될 것 같다.
320x100