mirror-chatterino2/src/common/FlagsEnum.hpp

83 lines
1.6 KiB
C++
Raw Normal View History

2018-01-28 03:29:42 +01:00
#pragma once
#include <type_traits>
namespace chatterino {
2018-01-28 15:28:02 +01:00
template <typename T, typename Q = typename std::underlying_type<T>::type>
2018-01-28 03:29:42 +01:00
class FlagsEnum
{
public:
FlagsEnum()
2018-08-10 18:56:17 +02:00
: value_(static_cast<T>(0))
2018-01-28 03:29:42 +01:00
{
}
2018-08-07 07:55:31 +02:00
FlagsEnum(T value)
2018-08-10 18:56:17 +02:00
: value_(value)
2018-01-28 03:29:42 +01:00
{
}
2018-08-07 07:55:31 +02:00
FlagsEnum(std::initializer_list<T> flags)
2018-01-28 03:29:42 +01:00
{
2018-10-21 13:43:02 +02:00
for (auto flag : flags)
{
2018-08-07 07:55:31 +02:00
this->set(flag);
}
2018-01-28 03:29:42 +01:00
}
2018-08-07 07:55:31 +02:00
bool operator==(const FlagsEnum<T> &other)
2018-01-28 03:29:42 +01:00
{
2018-08-10 18:56:17 +02:00
return this->value_ == other.value_;
2018-01-28 03:29:42 +01:00
}
2018-08-07 07:55:31 +02:00
bool operator!=(const FlagsEnum &other)
{
2018-08-10 18:56:17 +02:00
return this->value_ != other.value_;
}
2018-08-07 01:35:24 +02:00
void set(T flag)
{
2018-08-10 18:56:17 +02:00
reinterpret_cast<Q &>(this->value_) |= static_cast<Q>(flag);
2018-08-07 01:35:24 +02:00
}
void unset(T flag)
{
2018-08-10 18:56:17 +02:00
reinterpret_cast<Q &>(this->value_) &= ~static_cast<Q>(flag);
2018-08-07 01:35:24 +02:00
}
void set(T flag, bool value)
{
if (value)
this->set(flag);
else
this->unset(flag);
}
2018-08-07 07:55:31 +02:00
bool has(T flag) const
{
2018-08-10 18:56:17 +02:00
return static_cast<Q>(this->value_) & static_cast<Q>(flag);
2018-08-07 07:55:31 +02:00
}
bool hasAny(FlagsEnum flags) const
{
2018-08-10 18:56:17 +02:00
return static_cast<Q>(this->value_) & static_cast<Q>(flags.value_);
2018-08-07 07:55:31 +02:00
}
bool hasAll(FlagsEnum<T> flags) const
{
2018-08-10 18:56:17 +02:00
return (static_cast<Q>(this->value_) & static_cast<Q>(flags.value_)) &&
2018-08-07 07:55:31 +02:00
static_cast<Q>(flags->value);
}
bool hasNone(std::initializer_list<T> flags) const
{
2018-08-07 07:55:31 +02:00
return !this->hasAny(flags);
}
2018-08-07 07:55:31 +02:00
private:
2018-08-10 18:56:17 +02:00
T value_{};
2018-01-28 03:29:42 +01:00
};
2018-01-28 03:29:42 +01:00
} // namespace chatterino