如何重载运算符>>对于布尔值
我想将标量解析为布尔值。 这个例子有效:
#include <yaml.h>
#include <iostream>
#include <sstream>
#include <string>
void operator>> (const YAML::Node & node, bool & b)
{
std::string tmp;
node >> tmp;
std::cout << tmp << std::endl;
b = (tmp == "1") || (tmp == "yes");
}
int main()
{
bool b1, b2;
std::stringstream ss("key: да\notherkey: no");
YAML::Parser parser(ss);
YAML::Node doc;
parser.GetNextDocument(doc);
doc["key"] >> b1;
doc["otherkey"] >> b2;
std::cout << b1 << std::endl;
std::cout << b2 << std::endl;
return 0;
}
但在更复杂的情况下使用模板运算符:
YAML::operator>><bool> (node=..., value=@0x63f6e8) at /usr/include/yaml-cpp/nodeimpl.h:24
如果字符串不是“是”或“否”,我会得到“YAML::InvalidScalar”。
I want to parse scalar as bool.
This example works:
#include <yaml.h>
#include <iostream>
#include <sstream>
#include <string>
void operator>> (const YAML::Node & node, bool & b)
{
std::string tmp;
node >> tmp;
std::cout << tmp << std::endl;
b = (tmp == "1") || (tmp == "yes");
}
int main()
{
bool b1, b2;
std::stringstream ss("key: да\notherkey: no");
YAML::Parser parser(ss);
YAML::Node doc;
parser.GetNextDocument(doc);
doc["key"] >> b1;
doc["otherkey"] >> b2;
std::cout << b1 << std::endl;
std::cout << b2 << std::endl;
return 0;
}
But in more complicated case template operator is used:
YAML::operator>><bool> (node=..., value=@0x63f6e8) at /usr/include/yaml-cpp/nodeimpl.h:24
And I get 'YAML::InvalidScalar' if string in not 'yes' or 'no'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
yaml-cpp 默认情况下已读取
bool
,如 YAML 规范所指定。产生
true
,并且产生
false
。如果您想扩展或更改此行为(例如,让“да”也产生true
),正如您所发现的,在中重载operator >>
YAML
命名空间有效。它需要位于
YAML
命名空间中的原因(但仅适用于“更复杂的示例” - 意味着您不直接使用operator >>
调用operator >>
code>bool 参数)是 C++ 查找的工作方式。请参阅此答案到我的老问题以获得很好的解释。
yaml-cpp already reads
bool
s by default, as specified by the YAML spec.produce
true
, andproduce
false
. If you want to extend or change this behavior (for example, so that "да" also producestrue
), as you found out, overloadingoperator >>
in theYAML
namespace works.The reason it needs to be in the
YAML
namespace (but only for "more complicated examples" - meaning where you don't directly calloperator >>
with abool
argument) is the way C++ lookup works.See this answer to my old question for a great explanation.