我有一个库(围绕nlohmann / json封装),可以从JSON反序列化:
struct MyStruct {
int propertyA;
std::string propertyB;
std::vector<int> propertyC;
}
void from_json(const JSON::Node& json, MyStruct& s)
{
json_get(s.propertyA, "propertyA", json);
json_get(s.propertyB, "propertyB", json);
json_get(s.propertyC, "propertyC", json);
}
如您所见,这些定义中包含许多样板。我使用的ECS框架包含数百个我想反序列化的组件。我希望通过一个宏来简化它,例如:
struct MyStruct {
int propertyA;
std::string propertyB;
std::vector<int> propertyC;
JSON(MyStruct, propertyA, propertyB, propertyC);
};
}
我知道过手动重复宏N次的老式
__VA_ARGS__
方法,但我希望通过更通用/现代的方法避免这种情况。可变参数模板有可能吗?是否有更好的方法为此提供某种语法糖?我正在使用C++ 17编译器。
最佳答案
显然,a library确实可以满足您的需求!这是一个完整的示例:
#include <iostream>
#include <nlohmann/json.hpp>
#include <visit_struct/visit_struct.hpp>
struct MyStruct {
int propertyA;
std::string propertyB;
std::vector<int> propertyC;
};
VISITABLE_STRUCT(MyStruct, propertyA, propertyB, propertyC);
using nlohmann::json;
template <typename T>
std::enable_if_t<visit_struct::traits::is_visitable<std::decay_t<T>>::value>
from_json(const json &j, T &obj) {
visit_struct::for_each(obj, [&](const char *name, auto &value) {
// json_get(value, name, j);
j.at(name).get_to(value);
});
}
int main() {
json j = json::parse(R"(
{
"propertyA": 42,
"propertyB": "foo",
"propertyC": [7]
}
)");
MyStruct s = j.get<MyStruct>();
std::cout << "PropertyA: " << s.propertyA << '\n';
std::cout << "PropertyB: " << s.propertyB << '\n';
std::cout << "PropertyC: " << s.propertyC[0] << '\n';
}
关于c++ - 现代/通用方法来处理可变参数宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60133341/