c++ - 现代/通用方法来处理可变参数宏

标签 c++ macros variadic-templates variadic-macros

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

相关文章:

c++ - 使用 ACE_Service_Object

c++ - 我如何将 Octave (matlab 克隆)与 qt creator 集成

c++ - 类型、整型常量和模板模板参数的可变参数模板

c++ - 模板和函数参数数量相等

c++ - 数组成员的初始化程序无效

c++ - Const Ref to const 指针

c - 了解宏行为和原线程

clojure - 你能给我一些 -> 宏的现实例子吗?

parallel-processing - Julia 中以函数作为输入的宏

c++ - 参数包困惑