【发布时间】:2019-12-14 00:20:39
【问题描述】:
下面的类是一个顶层类,它带来了nlohman::json的所有好处,但提供了额外的功能。
#include <nlohmann/json.hpp>
class Other { /* ... */ };
class AbstractData : public nlohmann::json
{
public:
AbstractData (const nlohmann::json& json) : nlohmann::json(json) { }
Other createOther(const char* key) { /* create Other class using key */ }
std::string toString() { /* convert to string */ }
/* etc. */
};
但是我在使用operator[] 时遇到了问题。 默认我们有
AbstractData a;
auto& val = a["some_key"]; // val is nlohman::json::value_type&
因此val 失去了所有额外的功能。
当我们提供类函数operator[]
const AbstractData& AbstractData::operator[](const char* key) const
{
return nlohmann::json::operator[](key);
}
然后
AbstractData a;
auto& val = a["some_key"]; // val is AbstractData&
按预期工作。但是为了实现这一点,调用了复制构造函数AbstractData (const nlohmann::json& json)(这对于大对象来说效率很低)。这首先违背了返回引用的目的。
我看到过类似Add a method to existing C++ class in other file 的问题,但他们没有为我的具体问题提供帮助。
有什么建议吗?
【问题讨论】:
-
https://github.com/nlohmann/json#design-goals不包括可扩展性。不要将继承用于扩展!
标签: c++ function class inheritance c++17