开发者

How to overload operator>> for bool

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'.


yaml-cpp already reads bools by default, as specified by the YAML spec.

y, yes, true, on

produce true, and

n, no, false, off

produce false. If you want to extend or change this behavior (for example, so that "да" also produces true), as you found out, overloading operator >> in the YAML namespace works.

The reason it needs to be in the YAML namespace (but only for "more complicated examples" - meaning where you don't directly call operator >> with a bool argument) is the way C++ lookup works.

See this answer to my old question for a great explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜