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