mirror-chatterino2/src/common/UniqueAccess.hpp

89 lines
1.5 KiB
C++
Raw Normal View History

2018-07-14 14:24:18 +02:00
#pragma once
2018-08-02 14:23:27 +02:00
#include <boost/noncopyable.hpp>
2018-07-14 14:24:18 +02:00
#include <mutex>
#include <type_traits>
namespace chatterino {
template <typename T>
2018-08-02 14:23:27 +02:00
class AccessGuard : boost::noncopyable
2018-07-14 14:24:18 +02:00
{
public:
AccessGuard(T &element, std::mutex &mutex)
: element_(element)
, mutex_(mutex)
{
this->mutex_.lock();
}
~AccessGuard()
{
this->mutex_.unlock();
}
2018-08-02 14:23:27 +02:00
T *operator->() const
2018-07-14 14:24:18 +02:00
{
return &this->element_;
}
2018-08-02 14:23:27 +02:00
T &operator*() const
2018-07-14 14:24:18 +02:00
{
return this->element_;
}
private:
T &element_;
std::mutex &mutex_;
};
template <typename T>
class UniqueAccess
{
public:
2018-08-02 14:23:27 +02:00
// template <typename X = decltype(T())>
2018-07-14 14:24:18 +02:00
UniqueAccess()
: element_(T())
{
}
UniqueAccess(const T &element)
: element_(element)
{
}
UniqueAccess(T &&element)
: element_(element)
{
}
UniqueAccess<T> &operator=(const T &element)
{
this->element_ = element;
return *this;
}
UniqueAccess<T> &operator=(T &&element)
{
this->element_ = element;
return *this;
}
2018-08-02 14:23:27 +02:00
AccessGuard<T> access() const
2018-07-14 14:24:18 +02:00
{
return AccessGuard<T>(this->element_, this->mutex_);
}
2018-08-02 14:23:27 +02:00
template <typename X = T, typename = std::enable_if_t<!std::is_const_v<X>>>
AccessGuard<const X> accessConst() const
2018-07-15 20:28:54 +02:00
{
2018-08-02 14:23:27 +02:00
return AccessGuard<const T>(this->element_, this->mutex_);
2018-07-15 20:28:54 +02:00
}
2018-07-14 14:24:18 +02:00
private:
2018-07-15 20:28:54 +02:00
mutable T element_;
mutable std::mutex mutex_;
2018-07-14 14:24:18 +02:00
};
} // namespace chatterino