0

我正在玩某种共享对象框架。它使用 nlohmann::json 来提供消息传递和配置,并根据 json 配置加载消息处理程序和数据源。

由于我使用的值类都派生自基类 Value,因此我希望所有开发人员都可以在 lib 中创建自己的值类。因此,我需要一种机制来将这样的值分配给 json 对象。

但是,如果我只使用指向基类的指针,我怎么能做到这一点呢?

using json = nlohmann::json;

class Base
{
 public:
  Base () :str("Hurray") { };
 private:
  // const std::string() { return str; }
  std::string str;
};


class Derived1 : public Base
{
 public:
  Derived1() { myInt = 1; };
 public:
  int myInt;
};


void to_json(json& j, const Derived1& p) {
  j = json{{"Derived1", p.myInt}};
}

void from_json(const json& j, Derived1& p) {
  j.at("name").get_to(p.myInt);
}

int main(int argc, char* argv[]) {

  json myJ;
  Derived1 D1;
  myJ["D1"] = D1;
  std::cout << "myJ: " << myJ.dump() << std::endl;

  std::shared_ptr<Base> pointer = std::make_shared<Derived1>();
  json DerivedJson;
  //  DerivedJson["D1"] = *pointer;
  //  std::cout << "myJ" << DerivedJson.dump() << std::endl;
}

(示例也在https://github.com/Plurax/SOjsonassign上)

还有一个问题:我的代码目前使用的是自己的字符串包装器,它派生自 Baseclass。我曾经从提供“asString”的模板 Base 派生,返回我的字符串类,因为它在基类中不可用。

自己的字符串类的唯一原因是提供一个通用的值接口。是否有另一种方法来获得通用接口?

4

1 回答 1

2

您可以创建一个virtual json tojson() const;函数base,然后在派生类中覆盖它。然后,而不是使用*pointer,调用pointer->tojson()。类中的实现可以调用全局to_json函数,或者全局函数可以调用类中的。

于 2018-09-30T20:41:17.497 回答