Add std::pair conversion specialization.

This commit is contained in:
Jesse Beder
2013-04-02 21:04:17 -05:00
parent 0482463569
commit 097ac171c6
2 changed files with 48 additions and 2 deletions

View File

@@ -223,6 +223,38 @@ namespace YAML
}
};
// std::pair
template<typename T, typename U>
struct convert<std::pair<T, U> > {
static Node encode(const std::pair<T, U>& rhs) {
Node node(NodeType::Sequence);
node.push_back(rhs.first);
node.push_back(rhs.second);
return node;
}
static bool decode(const Node& node, std::pair<T, U>& rhs) {
if(!node.IsSequence())
return false;
if (node.size() != 2)
return false;
#if defined(__GNUC__) && __GNUC__ < 4
//workaround for GCC 3:
rhs.first = node[0].template as<T>();
#else
rhs.first = node[0].as<T>();
#endif
#if defined(__GNUC__) && __GNUC__ < 4
//workaround for GCC 3:
rhs.second = node[1].template as<U>();
#else
rhs.second = node[1].as<U>();
#endif
return true;
}
};
// binary
template<>
struct convert<Binary> {

View File

@@ -168,6 +168,18 @@ namespace Test
return true;
}
TEST StdPair()
{
std::pair<int, std::string> p;
p.first = 5;
p.second = "five";
YAML::Node node;
node["pair"] = p;
YAML_ASSERT((node["pair"].as<std::pair<int, std::string> >() == p));
return true;
}
TEST SimpleAlias()
{
YAML::Node node;
@@ -463,8 +475,9 @@ namespace Test
TEST ret;
try {
ret = test();
} catch(...) {
} catch(const std::exception& e) {
ret.ok = false;
ret.error = e.what();
}
if(ret.ok) {
passed++;
@@ -492,6 +505,7 @@ namespace Test
RunNodeTest(&Node::StdVector, "std::vector", passed, total);
RunNodeTest(&Node::StdList, "std::list", passed, total);
RunNodeTest(&Node::StdMap, "std::map", passed, total);
RunNodeTest(&Node::StdPair, "std::pair", passed, total);
RunNodeTest(&Node::SimpleAlias, "simple alias", passed, total);
RunNodeTest(&Node::AliasAsKey, "alias as key", passed, total);
RunNodeTest(&Node::SelfReferenceSequence, "self reference sequence", passed, total);