Nlohmann::json& 作为函数参数而不包含 json.hpp in header

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

我有一个 class,我想要一个使用 nlohmann::json& 作为参数的函数:

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

但我不想在我的 header 中包含 json.hpp 文件,只是我的 .cpp。如何在 header 中声明 nlohmann::json?我试过了:

namespace nlohmann
{
    class json;
}

但这似乎不起作用。

如果我们查看源代码,我们可以看到 json 是在 json_fwd.hpp 中定义的。

using json = basic_json<>;

jsonbasic_json 的别名,因此您需要在声明 json 之前转发声明 basic_json。如果您在 json_fwd.hpp 中向上滚动一点,您将看到 basic_json 的大量前向声明。所以如果你想在头文件中使用nlohmann::json &,你可以包含json_fwd.hpp.