Added (unspecified-type) bool conversions for Node (new API)

This commit is contained in:
Jesse Beder 2011-11-13 16:05:42 -06:00
parent d78d16532a
commit 5abfbf5aac
4 changed files with 48 additions and 0 deletions

View File

@ -0,0 +1,26 @@
#ifndef NODE_DETAIL_BOOL_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define NODE_DETAIL_BOOL_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once
#endif
namespace YAML
{
namespace detail
{
struct unspecified_bool {
struct NOT_ALLOWED;
static void true_value(NOT_ALLOWED*) {}
};
typedef void (*unspecified_bool_type)(unspecified_bool::NOT_ALLOWED*);
}
}
#define YAML_CPP_OPERATOR_BOOL()\
operator YAML::detail::unspecified_bool_type() const\
{\
return this->operator!() ? 0 : &YAML::detail::unspecified_bool::true_value;\
}
#endif // NODE_DETAIL_BOOL_TYPE_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@ -49,6 +49,11 @@ namespace YAML
m_pNode->set_null();
}
}
inline bool Node::IsDefined() const
{
return m_pNode ? m_pNode->is_defined() : true;
}
inline NodeType::value Node::Type() const
{

View File

@ -10,6 +10,7 @@
#include "yaml-cpp/node/ptr.h"
#include "yaml-cpp/node/type.h"
#include "yaml-cpp/node/detail/iterator_fwd.h"
#include "yaml-cpp/node/detail/bool_type.h"
#include <stdexcept>
namespace YAML
@ -29,11 +30,16 @@ namespace YAML
~Node();
NodeType::value Type() const;
bool IsDefined() const;
bool IsNull() const { return Type() == NodeType::Null; }
bool IsScalar() const { return Type() == NodeType::Scalar; }
bool IsSequence() const { return Type() == NodeType::Sequence; }
bool IsMap() const { return Type() == NodeType::Map; }
// bool conversions
YAML_CPP_OPERATOR_BOOL();
bool operator!() const { return !IsDefined(); }
// access
template<typename T> const T as() const;
const std::string& Scalar() const;

View File

@ -268,6 +268,16 @@ namespace Test
YAML_ASSERT(node[true].as<bool>() == false);
return true;
}
TEST AutoBoolConversion()
{
YAML::Node node;
node["foo"] = "bar";
YAML_ASSERT(static_cast<bool>(node["foo"]));
YAML_ASSERT(!node["monkey"]);
YAML_ASSERT(!!node["foo"]);
return true;
}
}
void RunNodeTest(TEST (*test)(), const std::string& name, int& passed, int& total) {
@ -312,6 +322,7 @@ namespace Test
RunNodeTest(&Node::TempMapVariable, "temp map variable", passed, total);
RunNodeTest(&Node::TempMapVariableAlias, "temp map variable alias", passed, total);
RunNodeTest(&Node::Bool, "bool", passed, total);
RunNodeTest(&Node::AutoBoolConversion, "auto bool conversion", passed, total);
std::cout << "Node tests: " << passed << "/" << total << " passed\n";
return passed == total;