userdata.h
1 /*
2 ** ClanLib SDK
3 ** Copyright (c) 1997-2015 The ClanLib Team
4 **
5 ** This software is provided 'as-is', without any express or implied
6 ** warranty. In no event will the authors be held liable for any damages
7 ** arising from the use of this software.
8 **
9 ** Permission is granted to anyone to use this software for any purpose,
10 ** including commercial applications, and to alter it and redistribute it
11 ** freely, subject to the following restrictions:
12 **
13 ** 1. The origin of this software must not be misrepresented; you must not
14 ** claim that you wrote the original software. If you use this software
15 ** in a product, an acknowledgment in the product documentation would be
16 ** appreciated but is not required.
17 ** 2. Altered source versions must be plainly marked as such, and must not be
18 ** misrepresented as being the original software.
19 ** 3. This notice may not be removed or altered from any source distribution.
20 **
21 ** Note: Some of the libraries ClanLib may link to may have additional
22 ** requirements or restrictions.
23 **
24 ** File Author(s):
25 **
26 ** Magnus Norddahl
27 */
28 
29 
30 #pragma once
31 
32 #include <memory>
33 
34 namespace clan
35 {
38 
40 {
41 public:
42  virtual ~UserDataBase() { }
43 };
44 
45 template<typename T>
46 class UserData : public UserDataBase
47 {
48 public:
49  UserData(const std::shared_ptr<T> &data) : data(data) { }
50  std::shared_ptr<T> data;
51 };
52 
55 {
56 public:
58  : user_data(nullptr)
59  {
60  }
61 
63  {
64  if (user_data)
65  {
66  user_data->~UserDataBase();
67  user_data = nullptr;
68  }
69  }
70 
71  template<typename T>
72  void set_data(const std::shared_ptr<T> &data)
73  {
74  if (user_data)
75  {
76  user_data->~UserDataBase();
77  user_data = nullptr;
78  }
79 
80  static_assert(sizeof(UserData<T>) <= 32, "userdata_storage is too small!");
81  user_data = new(userdata_storage) UserData<T>(data);
82  }
83 
84  template<typename T>
85  std::shared_ptr<T> get_data()
86  {
87  UserData<T> *d = dynamic_cast<UserData<T> *>(user_data);
88  if (d)
89  {
90  return d->data;
91  }
92  else
93  {
94  return std::shared_ptr<T>();
95  }
96  }
97 
98 private:
99  UserDataOwner(const UserDataOwner &that); // do not implement
100  UserDataOwner &operator=(const UserDataOwner &that); // do not implement
101 
102  UserDataBase *user_data;
103  char userdata_storage[32];
104 };
105 
106 }
virtual ~UserDataBase()
Definition: userdata.h:42
Definition: userdata.h:47
UserDataOwner()
Definition: userdata.h:57
~UserDataOwner()
Definition: userdata.h:62
std::shared_ptr< T > data
Definition: userdata.h:50
Helper class to store any shared_ptr as user data on an object.
Definition: userdata.h:55
std::shared_ptr< T > get_data()
Definition: userdata.h:85
void set_data(const std::shared_ptr< T > &data)
Definition: userdata.h:72
Definition: clanapp.h:36
UserData(const std::shared_ptr< T > &data)
Definition: userdata.h:49
Definition: userdata.h:40