首页 > 解决方案 > 从头文件中隐藏指针成员实现

问题描述

我正在使用一个- nlohmann/json 并希望有一个指向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_cast在这种情况下安全吗?

标签: c++templatesc++14

解决方案


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

namespace nlohmann { class json; }

编辑:我用过json_fwd.hpp。(https://github.com/nlohmann/json/blob/master/include/nlohmann/json_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;

推荐阅读