nlohmann可以自动兼容将C++的很多原生类型转换为json,甚至自定义类型也不需要太复杂的操作就可以转换为json,可以利用这一点将数据转换为string:
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
#include <tuple>
#include <iostream>
#include <concepts>
using namespace std;
using json = nlohmann::json;
template<typename T>
concept TO_JSONSTR = requires(T t)
{
json(t);
};
template<TO_JSONSTR T>
string toStr(T t)
{
json j = t;
return j.dump();
}
template<class T>
string toStr(T t)
{
cout<<"can't convert to string";
return "";
}
struct Person1{
string name = "xiaoming";
int sex = 1;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Person1, name, sex)
struct Person2{
string name = "xiaoming";
int sex = 1;
};
int main()
{
int a1 = 1;
auto s1 = toStr(a1);
cout<<s1<<endl;