【发布时间】:2020-04-23 02:26:17
【问题描述】:
我正在使用 library - 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_casting 指针)在这种情况下static_casting 安全吗?
【问题讨论】:
-
我想
class my_json和struct my_json是错字? -
通过
struct my_json : public nlohmann::json {};形式的继承,my_json *可以隐式转换为nlohmann::json *(即从派生到基)。反向(从基础到派生的转换)无效。在不知道为什么要尝试以错误的方向进行转换的情况下,实际上不可能就解决方案提出建议。 -
@ThomasCaissard - 在这种情况下,两者之间没有真正的区别。
class和struct是相同的,除了struct的默认访问和默认继承是public,class是private。 -
@Peter 我有一个成员集合,它也存储指向
my_json *的指针,还有一些内部函数希望在它们之间与my_json *进行通信(例如返回值或参数)。声明必须在标题中,所以我“卡住”了将其定义为my_json *而不是真正的类型。如果我static_cast<my_json*>编译它,那么它定义得很好(假设继承就是这样并且没有引入任何东西) -
static_cast 将起作用,甚至在需要时调整指针(例如,用于多重继承)。但是,如果您的指针不指向动态类型 my_json 的对象(或从它派生的类型),您将获得未定义的行为。