userdata.h
1 /*
2 ** ClanLib SDK
3 ** Copyright (c) 1997-2016 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 #pragma once
30 
31 #include <memory>
32 
33 namespace clan
34 {
37 
39  {
40  public:
41  virtual ~UserDataBase() { }
42  };
43 
44  template<typename T>
45  class UserData : public UserDataBase
46  {
47  public:
48  UserData(const std::shared_ptr<T> &data) : data(data) { }
49  std::shared_ptr<T> data;
50  };
51 
54  {
55  public:
57  : user_data(nullptr)
58  {
59  }
60 
62  {
63  if (user_data)
64  {
65  user_data->~UserDataBase();
66  user_data = nullptr;
67  }
68  }
69 
70  template<typename T>
71  void set_data(const std::shared_ptr<T> &data)
72  {
73  if (user_data)
74  {
75  user_data->~UserDataBase();
76  user_data = nullptr;
77  }
78 
79  static_assert(sizeof(UserData<T>) <= 32, "userdata_storage is too small!");
80  user_data = new(userdata_storage)UserData<T>(data);
81  }
82 
83  template<typename T>
84  std::shared_ptr<T> get_data()
85  {
86  UserData<T> *d = dynamic_cast<UserData<T> *>(user_data);
87  if (d)
88  {
89  return d->data;
90  }
91  else
92  {
93  return std::shared_ptr<T>();
94  }
95  }
96 
97  private:
98  UserDataOwner(const UserDataOwner &that); // do not implement
99  UserDataOwner &operator=(const UserDataOwner &that); // do not implement
100 
101  UserDataBase *user_data;
102  char userdata_storage[32];
103  };
104 
106 }
Definition: clanapp.h:35
UserData(const std::shared_ptr< T > &data)
Definition: userdata.h:48
UserDataOwner()
Definition: userdata.h:56
virtual ~UserDataBase()
Definition: userdata.h:41
Definition: userdata.h:45
std::shared_ptr< T > data
Definition: userdata.h:49
std::shared_ptr< T > get_data()
Definition: userdata.h:84
Helper class to store any shared_ptr as user data on an object.
Definition: userdata.h:53
void set_data(const std::shared_ptr< T > &data)
Definition: userdata.h:71
Definition: userdata.h:38
~UserDataOwner()
Definition: userdata.h:61