带可变参数的可变参数宏的现代/通用方法

问题描述 投票:1回答:1

我有一个库(围绕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);
};

}

[我知道老式的__VA_ARGS__方法是手动重复执行宏N次,但是我希望通过更通用的/现代的方法避免这种情况。

可变参数模板有可能吗?是否有更好的方法为此提供某种语法糖?我正在使用C ++ 17编译器。

c++ macros variadic-templates variadic-macros
1个回答
1
投票

显然,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';
}
© www.soinside.com 2019 - 2024. All rights reserved.