【问题标题】:Nlohmann::json& as function argument without including json.hpp in headerNlohmann::json& 作为函数参数,而不在标头中包含 json.hpp
【发布时间】:2021-04-06 23:44:28
【问题描述】:

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

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

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

namespace nlohmann
{
    class json;
}

但这似乎不起作用。

【问题讨论】:

  • 您能否详细说明“似乎不起作用”?它会产生编译器错误吗?链接器错误?函数中的行为不正确?
  • 怎么不行?你看到了什么错误?
  • 这是您要找的吗? en.cppreference.com/w/cpp/language/pimpl

标签: c++ forward-declaration nlohmann-json


【解决方案1】:

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

using json = basic_json<>;

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

【讨论】:

  • 有没有办法在不包括 json_fwd.hpp 的情况下做到这一点?
  • @ChipBurwell 是的,您可以复制并粘贴json_fwd.hpp 的内容,但这就是#include 所做的(我不建议这样做)。 json_fwd.hpp 标头正是为此目的而创建的,转发 json 而不包括巨大的 json.hpp 标头。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
相关资源
最近更新 更多