从头文件中隐藏指针成员的实现。

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

我使用的是 图书馆 - nlohmannjson,并希望有一个指向 json 供内部使用。

我想避免将整个库作为编译时的依赖,所以我考虑使用一个指针来指向一个向前声明的结构

在页眉

struct my_json; // forward declare 

std::unique_ptr<my_json> memberJson;

在cpp中。

struct my_json : public nlohmann::json {};

但问题是,当我试图在类中使用它时,我得到的是:

error C2440: '=': cannot convert from 'nlohmann::json *' to 'my_json *'

当试图将一个结果的地址分配给 reference operator[](const typename object_t::key_type& key) 回到 my_json *

error C2440: 'initializing': cannot convert from 'nlohmann::basic_json<std::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer>' to 'my_json  &'

试图分配结果的时候 reference operator[](const typename object_t::key_type& key)my_json & 径直

有什么优雅的解决方案吗? (如果我想避开 reinterpret_cast的指针)是 static_casting在这种情况下是安全的?

c++ templates c++14
1个回答
3
投票

你为什么不转发声明 nlohmann::json?

namespace nlohmann { class json; }

编辑:我已经用 json_fwd.hpp.(https:/github.comnlohmannjsonblobmasterincludenlohmannjson_fwd.hpp。)

标题:

#pragma once
#include "json_fwd.hpp"
#include <memory>

class A {
    std::unique_ptr<nlohmann::json> ptr;

    public:
        A();
        ~A();
};

执行。

#include "Header.h"
#include "json.hpp"

A::A() :
    ptr(std::make_unique<nlohmann::json>()) {

    (*ptr)["Hallo"] = 2;
}

A::~A() = default;
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.