【问题标题】:any means of returning bool for yaml variables in yaml-cpp?在yaml-cpp中为yaml变量返回bool的任何方法?
【发布时间】:2021-05-13 07:04:00
【问题描述】:

我有一个用于禁用特定代码路径的配置文件。我刚刚在 yaml 文件中添加了一个 bool 选项,并且很难弄清楚 yaml-cpp 如何处理这些选项。文档比首选的要轻一些,我看不到任何适合我用例的Node。我可以手动解析返回为truefalse 的字符串,但这似乎是框架应该支持的,因为在规范中有多种写作风格truefalse。有没有办法从 yaml-cpp 中获取 bool 值?

IsScalar是我能找到的最接近的。

void LoadConfig(string file)
{
   Node config = LoadFile(file);
   string targetDirectory;
   bool compile;
   if (config["TargetDirectory"])
      targetDirectory = config["TargetDirectory"].Scalar();
   if (config["Compile"])
      compile = Config["Compile"].IsScalar(); 
}

【问题讨论】:

    标签: c++ yaml yaml-cpp


    【解决方案1】:

    你想要模板as()方法:

    config["Compile"].as<bool>()
    

    或者使用默认值在一行而不是三行中完成所有操作的更简洁的方法(这也解决了您潜在的未初始化变量错误):

    bool compile = config["Compile"].as<bool>(false);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2020-09-10
      • 2013-11-28
      • 1970-01-01
      • 2014-05-31
      • 2020-10-14
      相关资源
      最近更新 更多