00001 #ifndef TYPELIB_VALUE_CAST_HH 00002 #define TYPELIB_VALUE_CAST_HH 00003 00004 #include "value.hh" 00005 #include "normalized_numerics.hh" 00006 00007 namespace Typelib 00008 { 00013 template<typename T> 00014 class CastingVisitor : public ValueVisitor 00015 { 00016 bool m_found; 00017 T m_value; 00018 00019 bool visit_( typename normalized_numeric_type<T>::type& v) 00020 { 00021 m_value = v; 00022 m_found = true; 00023 return false; 00024 } 00025 00026 public: 00027 CastingVisitor() 00028 : ValueVisitor(false), m_found(false), m_value() {}; 00029 T& apply(Value v) 00030 { 00031 m_found = false; 00032 ValueVisitor::apply(v); 00033 if (!m_found) 00034 throw BadValueCast(); 00035 00036 return m_value; 00037 } 00038 }; 00039 00042 template<typename T> 00043 T& value_cast(Value v) 00044 { 00045 CastingVisitor<T> caster; 00046 return caster.apply(v); 00047 } 00048 00051 template<typename T> 00052 T& value_cast(void* ptr, Type const& type) 00053 { return value_cast<T>(Value(ptr, type)); } 00054 } 00055 00056 #endif