The below class is meant to be a top-layer class which brings all the benefits of nlohman::json but offers additional functions.
#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. */
};
But I ran into issues when using operator[]
. By default we have
AbstractData a;
auto& val = a["some_key"]; // val is nlohman::json::value_type&
and thus val
loses all the extra functions.
When we provide a class function operator[]
const AbstractData& AbstractData::operator[](const char* key) const
{
return nlohmann::json::operator[](key);
}
then
AbstractData a;
auto& val = a["some_key"]; // val is AbstractData&
works as expected. But in order to achieve this, the copy constructor AbstractData (const nlohmann::json& json)
is called (which is very inefficient for large objects). And this defeats the purpose of returning a reference in the first place.
I've seen questions like this one Add a method to existing C++ class in other file but they didn't offer help with my specific problem.
Any advice?