Skip to content

How do I forward nlohmann::json declaration? #899

Description

@aquacrew

Hello everybody,

I'm having a question - let me describe the scenario:

I plan to use JSON for Modern C++ to serialize objects used in a library. Other projects using this library should have no knowledge about the method used to save data. So it should be possible to replace the mechanismn by something else in the future without any change of code on the client side. Therefor I don't want to include json.hpp in my library header files.
But forward declaration failed - maybe you can help me to do it the right way. I tried

namespace nlohmann {
  class json;
}

Error: using typedef-name 'using json = class nlohmann::basic_json<>' after 'class'

Then I tried

namespace nlohmann {
  template<class T> class basic_json;
  using json = basic_json<>;
}

Error: wrong number of template arguments (0, should be 1)

I'm aiming to create an abstract template, which can be specialized in classes to be serialized.

namespace MyTest {
  template<class T> class JSON {
  protected:
    virtual void Serialize(nlohmann::json&, const T&) const = 0;
    virtual void Deserialize(const nlohmann::json&, T&)     = 0;
  };
}

Then I want to use it this way:

namespace MyTest {
  class Attribute : public JSON<Attribute> {
  private:
    virtual void                  Serialize(nlohmann::json&, const Attribute&) const;
    virtual void                  Deserialize(const nlohmann::json&, Attribute&);
  public:
    virtual void                  Serialize() const;
    virtual void                  Deserialize();
  };
}

I would be happy to have an answer for my question or any suggestions how to achieve my goal. Mybe you could add info about forward declaration to the description.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions