This repository has been archived on 2019-12-07. You can view files and clone it, but cannot push or open issues or pull requests.
dungeon-gunner/source/util/Yaml.h

82 lines
1.5 KiB
C
Raw Normal View History

/*
* Yaml.h
*
* Created on: 06.10.2012
* Author: Felix
*/
#ifndef DG_YAML_H_
#define DG_YAML_H_
2012-12-22 14:10:26 +00:00
#include <string>
#include <fstream>
#include <yaml-cpp/yaml.h>
2013-03-30 12:38:25 +00:00
#include "Log.h"
#include "Vector.h"
2013-03-30 12:38:25 +00:00
/**
* Interface to a YAML file.
*/
class Yaml {
public:
explicit Yaml(const std::string& filename);
~Yaml();
2012-12-22 14:10:26 +00:00
std::string getFilename() const;
2012-12-22 14:10:26 +00:00
static void setFolder(const std::string& folder);
template <typename T>
2012-12-22 14:10:26 +00:00
T get(const std::string& key, const T& defaultValue) const;
private:
2012-12-22 14:10:26 +00:00
static std::string mFolder;
2012-12-22 14:10:26 +00:00
std::string mFilename;
std::ifstream mFile;
YAML::Node mNode;
};
/**
* Stream output operators to specialize Yaml::get for other types.
2013-03-30 12:38:25 +00:00
* Error handling is done in Yaml::get.
*/
namespace {
void operator>>(const YAML::Node& node, Vector2i& vector) {
node[0] >> vector.x;
node[1] >> vector.y;
}
void operator>>(const YAML::Node& node, Vector2f& vector) {
node[0] >> vector.x;
node[1] >> vector.y;
}
};
/**
2013-03-30 12:38:25 +00:00
* Gets a value of a specified type by key. Returns default value on error.
*
* @param key The string by which to select the return value.
* @tparam T The type of the return value.
* @return The value of the specified key.
*/
template <typename T>
2012-12-22 14:10:26 +00:00
T Yaml::get(const std::string& key, const T& defaultValue) const {
2013-03-30 12:38:25 +00:00
try {
if (const YAML::Node* node = mNode.FindValue(key)) {
T value;
*node >> value;
return value;
}
2013-04-04 21:13:08 +00:00
else
return defaultValue;
}
catch(YAML::Exception&) {
return defaultValue;
}
};
#endif /* DG_YAML_H_ */