From: Thomas Geymayer Date: Sun, 3 Nov 2013 19:11:06 +0000 (+0100) Subject: SGPropertyNode: extract enum value with getValue X-Git-Url: https://git.mxchange.org/?a=commitdiff_plain;h=353b7e4438ff28f35f92844694d89914c8fe063c;p=simgear.git SGPropertyNode: extract enum value with getValue --- 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);