skullc-peripherals/Utility/Inc/utility_staticpointer.hpp
Erki 0ba9416a57
All checks were successful
continuous-integration/drone/push Build is passing
gitea/skullc-peripherals/pipeline/head This commit looks good
Add get() functionality to static_pointer
2022-06-30 19:46:56 +03:00

82 lines
1.4 KiB
C++

/*
* utility_staticpointer.hpp
*
* Created on: Jun 8, 2021
* Author: erki
*/
#ifndef SKULLC_UTILITY_STATICPOINTER_HPP_
#define SKULLC_UTILITY_STATICPOINTER_HPP_
#include <new>
#include <utility>
#include <utility_assert.hpp>
namespace Utility
{
template<typename T>
struct StaticPointer
{
using value_type = T;
alignas(value_type) unsigned char storage[sizeof(value_type)];
template<class... Args>
value_type& setup(Args&&... args)
{
initialized_ = true;
return *(new (storage) value_type(std::forward<Args>(args)...));
}
const value_type& operator*() const
{
return *reinterpret_cast<T*>(storage);
}
value_type& operator*()
{
return *reinterpret_cast<T*>(storage);
}
value_type* operator->() noexcept
{
return reinterpret_cast<value_type*>(storage);
}
const value_type* operator->() const noexcept
{
return reinterpret_cast<value_type*>(storage);
}
constexpr explicit operator bool() const
{
return isInitialized();
}
constexpr bool isInitialized() const
{
return initialized_;
}
value_type* get()
{
SKULLC_ASSERT_DEBUG(initialized_);
return reinterpret_cast<value_type*>(storage);
}
const value_type* get() const
{
SKULLC_ASSERT_DEBUG(initialized_);
return reinterpret_cast<const value_type*>(storage);
}
private:
bool initialized_ = false;
};
}// namespace Utility
#endif /* SKULLC_UTILITY_STATICPOINTER_HPP_ */