1
0
mirror of https://gitlab.com/OpenMW/openmw.git synced 2025-01-30 12:32:36 +00:00

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

72 lines
1.9 KiB
C++
Raw Normal View History

#ifndef AISTATE_H
#define AISTATE_H
#include "aistatefwd.hpp"
#include "aitemporarybase.hpp"
#include <memory>
2014-10-10 23:28:49 +02:00
namespace MWMechanics
{
2014-10-10 23:28:49 +02:00
/** \brief stores one object of any class derived from Base.
* Requesting a certain derived class via get() either returns
2014-10-10 23:28:49 +02:00
* the stored object if it has the correct type or otherwise replaces
* it with an object of the requested type.
*/
template <class Base>
class DerivedClassStorage
{
2014-10-10 23:28:49 +02:00
private:
std::unique_ptr<Base> mStorage;
2014-10-10 23:28:49 +02:00
public:
/// \brief returns reference to stored object or deletes it and creates a fitting
template <class Derived>
Derived& get()
{
Derived* result = dynamic_cast<Derived*>(mStorage.get());
if (result == nullptr)
2014-10-10 23:28:49 +02:00
{
auto storage = std::make_unique<Derived>();
result = storage.get();
mStorage = std::move(storage);
2014-10-10 23:28:49 +02:00
}
2014-10-10 23:28:49 +02:00
// return a reference to the (new allocated) object
return *result;
}
/// \brief returns pointer to stored object in the desired type
template <class Derived>
Derived* getPtr() const
{
return dynamic_cast<Derived*>(mStorage.get());
}
template <class Derived>
void copy(DerivedClassStorage& destination) const
{
Derived* result = dynamic_cast<Derived*>(mStorage.get());
if (result != nullptr)
destination.store<Derived>(*result);
}
2014-10-10 23:28:49 +02:00
template <class Derived>
void store(const Derived& payload)
{
mStorage = std::make_unique<Derived>(payload);
2014-10-10 23:28:49 +02:00
}
/// \brief takes ownership of the passed object
template <class Derived>
void moveIn(std::unique_ptr<Derived>&& storage)
2014-10-10 23:28:49 +02:00
{
mStorage = std::move(storage);
}
};
}
#endif // AISTATE_H