Nlohmann::json& as function argument without including json.hpp in header

Viewed 364

I have a class where I want to have a function that uses nlohmann::json& as the argument:

class MyClass
{
public:
    void foo(nlohmann::json& node); 
};

But I don't want to include the json.hpp file in my header, just my .cpp. How can I declare the nlohmann::json in the header? I tried:

namespace nlohmann
{
    class json;
}

But that doesn't seem to work.

1 Answers

If we have a look at the source, we can see that json is defined in json_fwd.hpp.

using json = basic_json<>;

json is an alias for basic_json so you need to forward declare basic_json before you can declare json. If you scroll up a bit in json_fwd.hpp, you'll see the massive forward declaration for basic_json. So if you want to use nlohmann::json & in a header file, you can include json_fwd.hpp.

Related