Remote Call Framework 3.2
RCF/Any.hpp
1 
2 //******************************************************************************
3 // RCF - Remote Call Framework
4 //
5 // Copyright (c) 2005 - 2020, Delta V Software. All rights reserved.
6 // http://www.deltavsoft.com
7 //
8 // RCF is distributed under dual licenses - closed source or GPL.
9 // Consult your particular license for conditions of use.
10 //
11 // If you have not purchased a commercial license, you are using RCF
12 // under GPL terms.
13 //
14 // Version: 3.2
15 // Contact: support <at> deltavsoft.com
16 //
17 //******************************************************************************
18 
19 #ifndef INCLUDE_RCF_ANY_HPP
20 #define INCLUDE_RCF_ANY_HPP
21 
22 #include <memory>
23 
24 #include <RCF/Exception.hpp>
25 #include <RCF/Tools.hpp>
26 
27 namespace RCF
28 {
29  class AnyHolderBase;
30  typedef std::unique_ptr<AnyHolderBase> AnyHolderPtr;
31 
32  class AnyHolderBase
33  {
34  public:
35  virtual ~AnyHolderBase() {}
36  virtual AnyHolderPtr clone() const = 0;
37  };
38 
39  template<typename T>
40  class AnyHolder : public AnyHolderBase
41  {
42  public:
43  AnyHolder(const T& any) : mAny(any)
44  {}
45 
46  ~AnyHolder()
47  {}
48 
49  virtual AnyHolderPtr clone() const
50  {
51  return AnyHolderPtr(new AnyHolder<T>(mAny));
52  }
53 
54  T& get()
55  {
56  return mAny;
57  }
58 
59  private:
60  T mAny;
61  };
62 
64  class Any
65  {
66  public:
67 
69  Any()
70  {
71  }
72 
74  template<typename T>
75  Any(const T& t) : mAnyPtr(new AnyHolder<T>(t))
76  {
77  }
78 
80  Any(const Any& rhs)
81  {
82  if ( rhs.mAnyPtr )
83  {
84  mAnyPtr = rhs.mAnyPtr->clone();
85  }
86  }
87 
89  Any& operator=(const Any& rhs)
90  {
91  if ( this != &rhs )
92  {
93  mAnyPtr.reset();
94  if ( rhs.mAnyPtr )
95  {
96  mAnyPtr = rhs.mAnyPtr->clone();
97  }
98  }
99  return *this;
100  }
101 
103  template<typename T>
104  T& get()
105  {
106  if ( !mAnyPtr )
107  {
108  // TODO: literal
109  RCF_THROW(Exception("Any cast failed. Null value."));
110  }
111  AnyHolder<T> * pHolder = dynamic_cast<AnyHolder<T> *>(mAnyPtr.get());
112  if ( !pHolder )
113  {
114  // TODO: literal
115  RCF_THROW(Exception("Any cast failed. Type mismatch."));
116  }
117  return pHolder->get();
118  }
119 
120  private:
121  AnyHolderPtr mAnyPtr;
122  };
123 
124 } // namespace RCF
125 
126 #endif // ! INCLUDE_RCF_ANY_HPP
Generic container type used to hold arbitrary objects.
Definition: RCF/Any.hpp:64
Any(const T &t)
Constructs an Any instance holding a copy of t.
Definition: RCF/Any.hpp:75
Any(const Any &rhs)
Copy constructs an Any instance.
Definition: RCF/Any.hpp:80
Base class for all RCF exceptions.
Definition: Exception.hpp:64
Any()
Constructs an empty Any instance.
Definition: RCF/Any.hpp:69
Any & operator=(const Any &rhs)
Assigns an Any instance.
Definition: RCF/Any.hpp:89
Definition: AmiIoHandler.hpp:24