首页 > 解决方案 > 在yaml-cpp中为yaml变量返回bool的任何方法?

问题描述

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

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++yamlyaml-cpp

解决方案


你想要模板as()方法:

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

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

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

推荐阅读