【问题标题】:C++ version conflict for using nlohmann/json in drake在德雷克中使用 nlohmann/json 的 C++ 版本冲突
【发布时间】:2020-07-04 22:21:27
【问题描述】:

我最近发现 nlohmann/json 在 C++ 11 上运行。否则,由于使用更高 C++ 版本的不推荐行,它会给出一些语法错误。

bazel-out/k8-opt/bin/examples/collaboration_station/_virtual_includes/manipulation_station/drake/examples/manipulation_station/include/json.hpp:2149:30: error: redundant redeclaration of 'constexpr' static data member 'nlohmann::detail::static_const<T>::value' [-Werror=deprecated]
 constexpr T static_const<T>::value;
                              ^~~~~
bazel-out/k8-opt/bin/examples/collaboration_station/_virtual_includes/manipulation_station/drake/examples/manipulation_station/include/json.hpp:2145:24: note: previous declaration of 'nlohmann::detail::static_const<T>::value'
     static constexpr T value{};

我能够通过使用关键字来运行带有 nlohmann 的普通 c++ 文件

bazel run --cxxopt='-std=c++11

但是,如果我将 drake 合并到我的示例中,它不会运行(很可能是由于 C++ 版本低)

为了测试 nlohmann/json,我在他们的github page 上获取了位于 json/single_include/nlohmann/json.hpp 下的 json.hpp 文件。我确保#include json 文件。

有没有一种简单的方法可以将 nlohmann/json 或任何其他类型的 json 阅读器合并到 drake 中?

【问题讨论】:

  • 我正在使用带有 drake 的 C++17 进行编译,它对我来说似乎工作正常。您能否更具体地发布有关您面临的编译错误以及您如何使用 drake 的信息?
  • 错误的核心是我上面贴的。我似乎在工具/工作区下找到了一个名为 json 的外部文件,我决定使用它而不是 nlohmann,它现在可以使用。
  • 很抱歉跟进晚了,但很高兴您能够解决它!您是否有时间将您的解决方案发布为自我回答?
  • 是的,我刚刚发布了。希望能帮助到你。希望 Drake 以后可以更多地使用 Json 文件。

标签: drake nlohmann-json


【解决方案1】:

虽然这并没有解决 nlohmann 问题,但这是在 Drake 中解析 json 文件的替代方法。如果您发现每次更改变量时都重新编译 c++ 文件很烦人,那么使用 json 文件可能会很有用。

在 deps 下的 BUILD.bazel 文件中,写入

"@jsoncpp",

然后在您的 .cc 文件中,包括以下内容:

#include <fstream>
#include <jsoncpp/json/json.h>
#include "drake/common/find_resource.h"

现在编写你的 json 解析函数

Json::Value json_parser(){
  Json::Reader reader;
  Json::Value root;
  drake::log()->info("json parser activated.");
  
  // User does not have to specify /home/your_name/
  std::ifstream myfile(FindResourceOrThrow("drake/path_to_file/config.json"));
  myfile >> root;
  drake::log()->info("reading json config file completed.");
  return root;

  // Example of accessing **outside** of this function
  // Json::Value root = json_parser();
  // cout << root["name"].asString() << endl;
}

在本例中,json 文件的名称为“config.json”。随意将其更改为您想要的任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2019-08-07
    相关资源
    最近更新 更多