小编msc*_*rer的帖子

有没有办法使用 nlohmann_json lib 序列化异构向量?

堆栈溢出社区大家好!

我正在开发一个大量使用有趣的nlohmann_json库的项目,似乎我需要在特定类上添加继承链接,该类对象会在某一时刻被序列化。

我尝试了在库的 github Issues 页面上找到的不同建议,但无法使其工作。

这是我尝试过的虚拟代码:

#include <nlohmann/json.hpp>

#include <iostream>
#include <memory>
#include <vector>

using json = nlohmann::json;

namespace nlohmann {
    template <typename T>
    struct adl_serializer<std::unique_ptr<T>> {
        static void to_json(json& j, const std::unique_ptr<T>& opt) {
            if (opt) {
                j = *opt.get();
            } else {
                j = nullptr;
            }
        }
    };
}

class Base {
    public:
        Base() = default;
        virtual ~Base() = default;
        virtual void foo() const { std::cout << "Base::foo()" << std::endl; }
};

class Obj : …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance stdvector unique-ptr nlohmann-json

2
推荐指数
1
解决办法
963
查看次数

标签 统计

c++ ×1

inheritance ×1

nlohmann-json ×1

stdvector ×1

unique-ptr ×1