00001 #ifndef LUAPP_VAR_HPP
00002 #define LUAPP_VAR_HPP
00003
00004 #include "luapp_exception.hpp"
00005 #include <utils_refptr.hpp>
00006 #include <typeinfo>
00007
00008 namespace lua
00009 {
00010 typedef std::type_info var_type;
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 class var
00026 {
00027 public :
00028
00029
00030 var();
00031
00032
00033
00034
00035 template <class T>
00036 var(const T& mValue) : pValue_(new value<T>(mValue)) {}
00037
00038
00039
00040
00041 var(const var& mVar);
00042
00043 var& operator = (const var& mVar);
00044
00045 bool operator == (const var& mVar) const;
00046
00047 bool operator != (const var& mVar);
00048
00049
00050
00051
00052 void swap(var& mVar);
00053
00054
00055
00056
00057
00058
00059
00060
00061 template<class T>
00062 const T get() const
00063 {
00064 const value<T>* pValue = dynamic_cast<const value<T>*>(pValue_.get());
00065 if (pValue)
00066 {
00067 return pValue->mT_;
00068 }
00069 else
00070 {
00071 if (pValue_)
00072 throw lua::exception("var",
00073 "Conversion from type \""+std::string(pValue_->get_type().name())+
00074 "\" to \""+typeid(T).name()+"\" failed. Returning default "
00075 "value."
00076 );
00077
00078 return T();
00079 }
00080 }
00081
00082
00083
00084
00085
00086
00087 bool is_empty() const;
00088
00089
00090
00091
00092
00093 const var_type& get_type() const;
00094
00095
00096
00097
00098
00099 template<class T>
00100 bool is_of_type() const
00101 {
00102 if (pValue_)
00103 {
00104 return pValue_->get_type() == typeid(T);
00105 }
00106 else
00107 {
00108 return typeid(void) == typeid(T);
00109 }
00110 }
00111
00112
00113
00114
00115 std::string to_string() const;
00116
00117 static const var_type& VALUE_NONE;
00118 static const var_type& VALUE_INT;
00119 static const var_type& VALUE_UINT;
00120 static const var_type& VALUE_FLOAT;
00121 static const var_type& VALUE_DOUBLE;
00122 static const var_type& VALUE_BOOL;
00123 static const var_type& VALUE_STRING;
00124 static const var_type& VALUE_POINTER;
00125
00126 private :
00127
00128
00129
00130
00131 class value_base
00132 {
00133 public :
00134
00135 virtual ~value_base() {}
00136 virtual value_base* clone() const = 0;
00137 virtual const var_type& get_type() const = 0;
00138 };
00139
00140 template <class T>
00141 class value : public value_base
00142 {
00143 public :
00144
00145 #ifdef MSVC
00146
00147
00148
00149 #pragma warning( disable : 4396 )
00150 #endif
00151 friend const T var::get<>() const;
00152
00153 value(const T& mT) : mT_(mT) {}
00154
00155 value_base* clone() const
00156 {
00157 return new value(mT_);
00158 }
00159
00160 const var_type& get_type() const
00161 {
00162 return typeid(T);
00163 }
00164
00165 private :
00166
00167 T mT_;
00168 };
00169
00170
00171
00172
00173 utils::refptr<value_base> pValue_;
00174 };
00175 }
00176
00177 #endif