MyGUI  3.2.1
MyGUI_Any.h
Go to the documentation of this file.
1 /*
2  * This source file is part of MyGUI. For the latest info, see http://mygui.info/
3  * Distributed under the MIT License
4  * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
5  */
6 
7 // -- Based on boost::any, original copyright information follows --
8 // Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved.
9 //
10 // Distributed under the Boost Software License, Version 1.0.
11 // (See at http://www.boost.org/LICENSE_1_0.txt)
12 // -- End original copyright --
13 
14 #ifndef __MYGUI_ANY_H__
15 #define __MYGUI_ANY_H__
16 
17 #include "MyGUI_Prerequest.h"
18 #include "MyGUI_Diagnostic.h"
19 #include <algorithm>
20 
21 #include <typeinfo>
22 
23 namespace MyGUI
24 {
25 
64  {
65  public:
66  struct AnyEmpty { };
67  static AnyEmpty Null;
68 
69  Any();
70  Any(const Any::AnyEmpty& value);
71  Any(const Any& other);
72 
73  template<typename ValueType>
74  Any(const ValueType& value) :
75  mContent(new Holder<ValueType>(value))
76  {
77  }
78 
79  ~Any();
80 
81  Any& swap(Any& rhs);
82 
83  template<typename ValueType>
84  Any& operator = (const ValueType& rhs)
85  {
86  Any(rhs).swap(*this);
87  return *this;
88  }
89 
90  Any& operator = (const Any::AnyEmpty& rhs);
91  Any& operator = (const Any& rhs);
92 
93  bool empty() const;
94 
95  const std::type_info& getType() const;
96 
97  template<typename ValueType>
98  ValueType* castType(bool _throw = true) const
99  {
100  if (this->getType() == typeid(ValueType))
101  return &static_cast<Any::Holder<ValueType> *>(this->mContent)->held;
102  MYGUI_ASSERT(!_throw, "Bad cast from type '" << getType().name() << "' to '" << typeid(ValueType).name() << "'");
103  return nullptr;
104  }
105 
106  void* castUnsafe() const;
107 
108  private:
109  class Placeholder
110  {
111  public:
112  virtual ~Placeholder() { }
113 
114  public:
115  virtual const std::type_info& getType() const = 0;
116  virtual Placeholder* clone() const = 0;
117  };
118 
119  template<typename ValueType>
120  class Holder :
121  public Placeholder
122  {
123  public:
124  Holder(const ValueType& value) :
125  held(value)
126  {
127  }
128 
129  public:
130  virtual const std::type_info& getType() const
131  {
132  return typeid(ValueType);
133  }
134 
135  virtual Placeholder* clone() const
136  {
137  return new Holder(held);
138  }
139 
140  public:
141  ValueType held;
142 
143  private:
144  Holder& operator=(const Holder&);
145  };
146 
147  private:
148  Placeholder* mContent;
149  };
150 
151 } // namespace MyGUI
152 
153 #endif // __MYGUI_ANY_H__