c++ - 从头文件中隐藏指针成员实现
问题描述
我正在使用一个库- 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
在这种情况下安全吗?
解决方案
你为什么不转发声明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;
推荐阅读
- batch-file - 将闪存驱动器设置为变量
- css - 顺风分割颜色仅适用于divide-x
- reactjs - “gatsby-source-airtable”在运行 sourceNodes 生命周期时抛出错误
- ruby-on-rails - Docker重启卡在rails应用程序的循环中
- javascript - Display textbox when others option when other option is selected and save it to database in laravel
- monaco-editor - 需要自定义表达式的 Monaco 编辑器
- python - 如何检测一个图像是否在另一个图像中?
- java - 打开主jframe时如何关闭所有jframe
- java - 如何通过 java 套接字接收字节
- python - Django OTP 正文消息的正确路径是什么?