I am using RapidJSON to make a message class returned uniformly by http. The code
and message
field types of the message class are fixed, but the data
field type is variable, so I try to use templates...
Since RapidJSON does not automatically convert various JSON types, I write out the basic types separately:
bool intToJson(const std::string& key, int value)
{
spdlog::info("int: {}", value);
return true;
}
bool stringToJson(const std::string& key, const std::string& value)
{
spdlog::info("string: {}", value);
return true;
}
bool classToJson(const std::string& key, const JsonBase& value)
{
spdlog::info("class: {}", "");
return true;
}
message class definition:
template<typename T>
class Message
{
public:
void toJson();
private:
T data;
int code;
std::string msg;
}
Then use typeid to distinguish the template type in the toJson function, and then use different conversion json functions:
void toJson()
{
intToJson("code", code);
stringToJson("message", msg);
if (typeid(data) == typeid(int))
{
intToJson("data", data);
}
else if (typeid(data) == typeid(std::string))
{
stringToJson("data", data);
}
else
{
classToJson("data", data);
}
}
Finally, use it in the main function:
Message<std::string> msg(200, "success", "success");
msg.toJson();
I get an error: cannot convert argument 2 from 'T' to 'int'
what should I do? thank you!!
error C2664: 'bool intToJson(const std::string &,int)' : cannot convert argument 2 from 'T' to 'int'