Implement convenience functions for DataMap
See https://github.com/azerothcore/azerothcore-wotlk/pull/748#issuecomment-362411082 for more.
This commit is contained in:
@@ -12,20 +12,50 @@
|
|||||||
class DataMap
|
class DataMap
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
/**
|
||||||
|
* Base class that you should inherit in your script.
|
||||||
|
* Inheriting classes can be stored to DataMap
|
||||||
|
*/
|
||||||
class Base
|
class Base
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
virtual ~Base() = default;
|
virtual ~Base() = default;
|
||||||
};
|
};
|
||||||
|
|
||||||
template<class T> T* GetCustomData(std::string const & k) const {
|
/**
|
||||||
|
* Returns a pointer to object of requested type stored with given key or nullptr
|
||||||
|
*/
|
||||||
|
template<class T> T* Get(std::string const & k) const {
|
||||||
static_assert(std::is_base_of<Base, T>::value, "T must derive from Base");
|
static_assert(std::is_base_of<Base, T>::value, "T must derive from Base");
|
||||||
auto it = Container.find(k);
|
auto it = Container.find(k);
|
||||||
if (it != Container.end())
|
if (it != Container.end())
|
||||||
return dynamic_cast<T*>(it->second.get());
|
return dynamic_cast<T*>(it->second.get());
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
void SetCustomData(std::string const & k, Base* v) { Container[k] = std::unique_ptr<Base>(v); }
|
|
||||||
|
/**
|
||||||
|
* Returns a pointer to object of requested type stored with given key
|
||||||
|
* or default constructs one and returns that one
|
||||||
|
*/
|
||||||
|
template<class T, typename std::enable_if<std::is_default_constructible<T>{}, int>::type = 0>
|
||||||
|
T* GetDefault(std::string const & k) {
|
||||||
|
static_assert(std::is_base_of<Base, T>::value, "T must derive from Base");
|
||||||
|
if (T* v = Get<T>(k))
|
||||||
|
return v;
|
||||||
|
T* v = new T();
|
||||||
|
cont.emplace(k, std::unique_ptr<T>(v));
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores a new object that inherits the Base class with the given key
|
||||||
|
*/
|
||||||
|
void Set(std::string const & k, Base* v) { Container[k] = std::unique_ptr<Base>(v); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes objects with given key and returns true if one was removed, false otherwise
|
||||||
|
*/
|
||||||
|
bool Erase(std::string const & k) { cont.erase(k) != 0; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::unordered_map<std::string, std::unique_ptr<Base>> Container;
|
std::unordered_map<std::string, std::unique_ptr<Base>> Container;
|
||||||
|
|||||||
Reference in New Issue
Block a user