From 353b7e4438ff28f35f92844694d89914c8fe063c Mon Sep 17 00:00:00 2001 From: Thomas Geymayer Date: Sun, 3 Nov 2013 20:11:06 +0100 Subject: [PATCH] SGPropertyNode: extract enum value with getValue --- simgear/props/props.hxx | 51 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/simgear/props/props.hxx b/simgear/props/props.hxx index 8ec61000..ea722448 100644 --- a/simgear/props/props.hxx +++ b/simgear/props/props.hxx @@ -20,8 +20,10 @@ #include #include #include +#include #include +#include #if PROPS_STANDALONE #else @@ -1784,7 +1786,8 @@ private: // Convenience functions for use in templates template -T getValue(const SGPropertyNode*); +typename boost::disable_if, T>::type +getValue(const SGPropertyNode*); template<> inline bool getValue(const SGPropertyNode* node) { return node->getBoolValue(); } @@ -1819,6 +1822,52 @@ inline std::string getValue(const SGPropertyNode* node) return node->getStringValue(); } +namespace simgear +{ + /** + * Default trait for extracting enum values from SGPropertyNode. Create your + * own specialization for specific enum types to enable validation of values. + */ + template + struct enum_traits + { + /** + * Typename of the enum + */ + static const char* name() { return typeid(T).name(); } + + /** + * @return Default value (will be used if validation fails) + */ + static T defVal() { return T(); } + + /** + * @return Whether the given integer value has an enum value defined + */ + static bool validate(int) { return true; } + }; +} // namespace simgear + +/** Extract enum from SGPropertyNode */ +template +inline typename boost::enable_if, T>::type +getValue(const SGPropertyNode* node) +{ + typedef simgear::enum_traits Traits; + int val = node->getIntValue(); + if( !Traits::validate(val) ) + { + SG_LOG + ( + SG_GENERAL, + SG_WARN, + "Invalid value for enum (" << Traits::name() << ", val = " << val << ")" + ); + return Traits::defVal(); + } + return static_cast(node->getIntValue()); +} + inline bool setValue(SGPropertyNode* node, bool value) { return node->setBoolValue(value); -- 2.39.5