Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to provide function json& to_json() which is similar as 'void to_json(json&j, const CObject& obj)' ? #1650

Closed
akeyliu opened this issue Jun 24, 2019 · 2 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@akeyliu
Copy link

akeyliu commented Jun 24, 2019

  • Describe what you want to achieve.
    I've deifned functions to_json for user defined classes, i.e.
    class foo
    {
    friend inline void to_json(json& j, const foo& obj) {...}.
    }
    These code work well.
    But I wonder if we can define the function like 'json& to_json(void) {...}' as a memeber function in the class foo?
    The purpose for this function is that I want to use virtual function of basic class, and all derived classes can automatic define their reload funtion such as 'cout << to_json() << endl';
    If can, how to define this function?

  • Describe what you tried.

  • Describe which system (OS, compiler) you are using.
    Ubuntu 18.04 LTS, g++ 7.3;

  • Describe which version of the library you are using (release version, develop branch).
    the master version.

@nlohmann
Copy link
Owner

This works:

#include "json.hpp"
#include <iostream>

using json = nlohmann::json;

class Base
{
  public:
    virtual json as_json() const = 0;
};

class A : public Base
{
  public:
    json as_json() const override { return json("A"); }
};

class B : public Base
{
  public:
    json as_json() const override { return json("B"); }
};

void to_json(json& j, const Base& obj)
{
    j = obj.as_json();
}

int main()
{
    A a;
    B b;
    std::cout << json(a) << " " << json(b) << std::endl;
}

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Jun 24, 2019
@akeyliu
Copy link
Author

akeyliu commented Jun 24, 2019

Thank a lot, and I confirmed it's OK for me.

@akeyliu akeyliu closed this as completed Jun 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants