问题描述
我有一个类,我想要一个使用 nlohmann::json& 作为参数的函数:
class MyClass
{
public:
void foo(nlohmann::json& node);
};
但我不想在我的头文件中包含 json.hpp 文件,只包含我的 .cpp。如何在标头中声明 nlohmann::json ?我试过了:
namespace nlohmann
{
class json;
}
但这似乎不起作用。
解决方法
如果我们查看源代码,我们可以看到 json
是在 json_fwd.hpp 中定义的。
using json = basic_json<>;
json
是 basic_json
的别名,因此您需要先转发声明 basic_json
,然后才能声明 json
。如果您在 json_fwd.hpp
中向上滚动一点,您会看到 basic_json
的大量前置声明。因此,如果您想在头文件中使用 nlohmann::json &
,您可以包含 json_fwd.hpp
。