diff --git a/include/yaml-cpp/node/impl.h b/include/yaml-cpp/node/impl.h index 312281f..e721be9 100644 --- a/include/yaml-cpp/node/impl.h +++ b/include/yaml-cpp/node/impl.h @@ -163,6 +163,14 @@ inline T Node::as(const S& fallback) const { return as_if(*this)(fallback); } +template +inline bool Node::into(T& target) const { + if (!this->IsDefined()) + return false; + target = this->as(); + return true; +} + inline const std::string& Node::Scalar() const { if (!m_isValid) throw InvalidNode(m_invalidKey); diff --git a/include/yaml-cpp/node/node.h b/include/yaml-cpp/node/node.h index c9e9a0a..e1f7a48 100644 --- a/include/yaml-cpp/node/node.h +++ b/include/yaml-cpp/node/node.h @@ -66,6 +66,9 @@ class YAML_CPP_API Node { T as() const; template T as(const S& fallback) const; + template + bool into(T& target) const; + const std::string& Scalar() const; const std::string& Tag() const; diff --git a/test/node/node_test.cpp b/test/node/node_test.cpp index 4f577c8..e221bae 100644 --- a/test/node/node_test.cpp +++ b/test/node/node_test.cpp @@ -645,6 +645,28 @@ TEST(NodeTest, AccessNonexistentKeyOnConstNode) { ASSERT_FALSE(other["5"]); } +TEST(NodeTest, IntoExists) { + Node node; + node["A"] = 4; + + int dest = 5; + bool res = node["A"].into(dest); + + ASSERT_TRUE(res); + EXPECT_EQ(dest, 4); +} + +TEST(NodeTest, IntoMissing) { + Node node; + node["A"] = 4; + + int dest = 5; + bool res = node["B"].into(dest); + + ASSERT_FALSE(res); + EXPECT_EQ(dest, 5); +} + class NodeEmitterTest : public ::testing::Test { protected: void ExpectOutput(const std::string& output, const Node& node) {