Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #ifndef XDISPATCH_ANY_STRUCT_H_
00024 #define XDISPATCH_ANY_STRUCT_H_
00025
00031 #ifndef __XDISPATCH_INDIRECT__
00032 #error "Please #include <xdispatch/dispatch.h> instead of this file directly."
00033 #endif
00034
00035 #include <typeinfo>
00036
00037 __XDISPATCH_BEGIN_NAMESPACE
00038
00039
00049 struct any {
00050
00051 any() : stored(0) {}
00052 template<typename Type> any(const Type& val) : stored(new holder<Type>(val)) {}
00053 any(const any& other) : stored(other.stored ? other.stored->clone() : 0 ) {}
00054 virtual ~any() { delete stored; }
00055
00056 any & swap(any & v)
00057 {
00058 std::swap(stored, v.stored);
00059 return *this;
00060 }
00061
00062 template<typename OtherType>
00063 any & operator=(const OtherType & v)
00064 {
00065 any(v).swap(*this);
00066 return *this;
00067 }
00068
00069 any & operator=(any v)
00070 {
00071 v.swap(*this);
00072 return *this;
00073 }
00074
00075 template<typename TargetType>
00076 TargetType cast() const {
00077 if(stored->type() == typeid(TargetType))
00078 return static_cast< holder<TargetType>* >(stored)->value;
00079 else
00080 throw std::bad_cast();
00081 }
00082
00083 private:
00084
00085 struct place_holder {
00086 virtual ~place_holder() {}
00087 virtual place_holder * clone() const = 0;
00088 virtual const std::type_info & type() const = 0;
00089 };
00090
00091 template <typename Type>
00092 struct holder : public place_holder {
00093 holder (const Type& val) : value(val) {}
00094
00095 virtual place_holder * clone() const {
00096 return new holder(value);
00097 }
00098
00099 virtual const std::type_info & type() const {
00100 return typeid(Type);
00101 }
00102
00103 Type value;
00104
00105 private:
00106 holder & operator=(const holder&);
00107 };
00108
00109 place_holder* stored;
00110 };
00111
00112 __XDISPATCH_END_NAMESPACE
00113
00116 #endif
00117